Search in Rotated Sorted Array

思路与Search in Rotated Sorted Array II相同

不同的是,这里数组中没有重复的数,所以也就不用单独考虑A[middle] = A[low]或A[middle] = A[high]的情况了。

public int search(int[] A, int target) {
        int length = A.length;
        if(length == 0)return -1;
        int low = 0;
        int high = length-1;
        int middle = 0;
        while(low <= high){
           middle = (low+high)/2;
           if(A[middle] == target)return middle;
           if(A[middle] >= A[low]){
               if(target >= A[low] && target < A[middle]){
                   high = middle-1;
               }else{
                   low = middle+1;
               }
           }else{
               if(target > A[middle] && target <= A[high]){
                   low = middle+1;
               }else{
                   high = middle-1;
               }
           }
        }
        return -1;
    }


你可能感兴趣的:(Search in Rotated Sorted Array)