给定一个已经排好序的字符串数组,空字符串散布在该数组中,编写一个函数寻找一个 给定字符串的位置。
public static int getIndex(String[] strs, String str){
if (strs == null || strs.length == 0 || str == null) {
return -1;
}
int start = -1;
int end = strs.length;
int i = 0;
while(start + 1 < end){
int mid = start + (end - start) / 2; //此写法和防止相加越界
if(strs[mid] != null){
if (strs[mid].compareTo(str) < 0) {
start = mid;
}else{
end = mid;
}
}else{
i = mid; //用i记录当前mid位置,然后往左边找第一个不为null的字符
while(strs[i] == null && --i >= start+1);
if (i < start+1 || strs[i].compareTo(str) < 0) {
start = mid;
}else{
end = i;
}
}
}
if (start+1 >= strs.length || !strs[start+1].equals(str)) {
return -1;
}
return start+1;
}