尽可能使用二分查找
假设在 left right 之间查找
关键是mid处理过程 导致 left 跟 right 的改变 控制去哪里寻找
分如下情况:
若 mid处 不为空,并且 此处就是 str 那么记下 mid ,同时把right-1 (往左寻找)
若 mid处不为空,并且此处不是str,比较字典顺序
若 mid处为空, 则通过while控制向左边移动,左边没有元素,或者找到的字典顺序小于str,left=mid+1
字典顺序大于str 或者等于 str 此时 res = strs[i].equals(str) ? i : res 然后right=i-1; 注意是i-1 此处的位置-1
package TT;import java.awt.List;public class Test3 {public static int getIndex (String[] strs, String str){if(strs==null || strs.length==0 ||str ==null){return -1;}int res = -1;int left =0;int right = strs.length;int mid = 0;int i =0;while(left <= right){mid=(left+right)/2;if(strs[mid]!=null && strs[mid].equals(str)){res = mid;right = mid-1;}else if(strs[mid]!=null){if(strs[mid].compareTo(str)<0){left = mid+1;}else {right = mid-1;}}else{i = mid; //把此时的mid记下了while(strs[i]==null && --i>=left);if(i<left || strs[i].compareTo(str)<0){left = mid+1;}else{res =strs[i].equals(str) ? i :res;right = i-1;}}}return res;}public static void main(String[] args){String[] objects = new String[6];objects[0]=null;objects[1]="b";objects[2]=null;objects[3]="b";objects[4]=null;objects[5]="a";String s = "b";int a = getIndex(objects,s);System.out.println(a);} }