有个排序后的字符串数组,其中散布着一些空字符串 ,编写一个方法,找出给定字符串(肯定不是空字符串)的索引。
有个排序后的字符串数组,其中散布着一些空字符串 ,编写一个方法,找出给定字符串(肯定不是空字符串)的索引。
解题思路:二分查找法。
/**
* @author Matthew
* @create 2021-03-27 8:53
*/
public class Case04_TeShuYouXuShuZu {
public static void main(String[] args) {
String[] arr = {"a", "", "ac", "", "ad", "", "b", "", "ba"};
int result = indexOf(arr, "b");
System.out.println("该字符的索引为:" + result);//索引值是从0开始计算
}
private static int indexOf(String[] arr, String s) {
int begin = 0;
int end = arr.length - 1;
while (begin <= end) {
int indexOfMid = (begin + end) / 2;
while (arr[indexOfMid].equals("")) {
indexOfMid++;
//输入非序列中的数后,防止陷入死循环
if (indexOfMid > end) {
return -1;
}
}
if (arr[indexOfMid].compareTo(s) > 0) {
end = indexOfMid - 1;
} else if (arr[indexOfMid].compareTo(s) < 0) {
begin = indexOfMid + 1;
} else {
return indexOfMid;
}
}
return -1;
}
}