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;
}
|
评论