在有空字符串的有序字符串数组中查找

题目:有个排序后的字符串,其中散布着一些空字符串,编写一个方法,找出给定字符串(肯定不是空字符串)的索引。

代码:

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

}

猜你喜欢

转载自www.cnblogs.com/xiaoyh/p/10261924.html