Cracking Coding Interview - 10.5 Sparse Search

Sparse Search: Given a sorted array of strings that is interspersed with empty strings, write a method to find the location of a given string.

Example

1
2
Input:  ball, {"at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""}
Output: 4

Hints: #256

解法1

不能直接用二分法,因为mid可能是"",那么你就不知道下一步应该到左边找还是右边找了。

能够想到的简单办法是如果mid是空串,那么就往左找非空串作为mid。如果左边找不到那么就往右边找mid。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public int sparseSearch(String[] array, String str) {
  return sparseSearch(array, str, 0, array.length);
}

private int sparseSearch(String[] array, String str, int start, int end) {
  if (start > end) {
    return -1;
  }
  int mid = (start + end) / 2;
  if (array[mid] == "") {
    int newMid = leftNonEmpty(array, mid);
    if (newMid == -1) {
      newMid = rightNonEmpty(array, mid);    
    }
    if (newMid == -1) {
      // 说明左右两边都是空串
      return -1;
    }
    mid = newMid;
  }
  
  if (array[mid] == str) {
    return mid;
  }
  if (array[mid] < str) {
    return sparseSearch(array, str, mid + 1, end);
  }
  return sparseSearch(array, str, start, mid - 1);
}

private int leftNonEmpty(String[] array, int mid, int start) {
  while (mid >= start) {
    if (array[mid] != "") {
      return mid;
    }
    mid--;
  }
  return -1;
}

private int rightNonEmpty(String[] array, int mid, int end) {
  while (mid <= end) {
    if (array[mid] != "") {
      return mid;
    }
    mid++;
  }
  return -1;
}

版权

评论