在有空字串的有序字串陣列中查詢
阿新 • • 發佈:2019-01-13
題目:有個排序後的字串,其中散佈著一些空字串,編寫一個方法,找出給定字串(肯定不是空字串)的索引。
程式碼:
public class 特殊有序陣列中查詢 { public static void main(String[] args) { // TODO Auto-generated method stub String [] arr = {"a","","ac","","ad","b","","ba"}; int res = indexOf(arr,"abc"); System.out.println(res); }private static int indexOf(String[] arr, String target) { int begin = 0; int end = arr.length - 1 ; while(begin<=end){ int indexOfMid = begin + ((end-begin)>>1); while(arr[indexOfMid].equals("")){ indexOfMid++;// 千萬要注意 if (indexOfMid>end) { return -1; } } if (arr[indexOfMid].compareTo(target)>0) { end = indexOfMid - 1; }else if (arr[indexOfMid].compareTo(target)<0) { begin = indexOfMid +1; }else { return indexOfMid; } } return -1; } }