首页 > 代码库 > Search in Rotated Sorted Array

Search in Rotated Sorted Array

O(logN)

Important Point:

Once the target is in one section, use the point in that section as benchmark

In this problem, if the target >= startVal, use A[mid] < startVal to throw the other section.

public class Solution {
    /** 
     *@param A : an integer rotated sorted array
     *@param target :  an integer to be searched
     *return : an integer
     */
    public int search(int[] A, int target) {
        // write your code here
        if (A == null || A.length == 0) {
            return -1;
        }
        
        int start = 0;
        int end = A.length - 1;
        int startVal = A[start];
        int endVal = A[end];
        
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (A[mid] == target) {
                    return mid;
            }
            if (target >= startVal) {
               if (A[mid] < startVal || A[mid] > target) {
                    end = mid;
                } else {
                    start = mid;
                }
            } else {
                if (A[mid] > endVal || A[mid] < target) {
                    start = mid;
                } else {
                    end = mid;
                }
            }
        }
        
        if (A[start] == target) {
            return start;
        }
        if (A[end] == target) {
            return end;
        }
        return -1;
    }
}

 

Search in Rotated Sorted Array