[leetcode]in Rotated Sorted Array

class Solution {
public:
    int search(int A[], int n, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int start = 0;
        int end = n-1;
        int mid;
        
        while(start <= end){
            mid = (start+end)/2;
            if(A[mid] == target) return mid;
            
            if(A[start] <= A[mid]){
                //first half is sorted
                if(target >= A[start] && target < A[mid]){
                    end = mid-1;
                }else{
                    start = mid + 1;
                }
            }else{
                //second half is sorted
                if(target > A[mid] && target <= A[end]){
                    start = mid + 1;
                }else{
                    end = mid-1;
                }
            }
        }
        
        return -1;
       
    }
};

你可能感兴趣的:([leetcode]in Rotated Sorted Array)