10.3 Search in Rotated Array

Without duplicates the code will run O(logn), however, if there are lots of duplicates it will run in O(n).

    bool search(vector<int> &A, int target) {
        // write your code here
        int lo = 0;
        int hi = A.size()-1;
        while(lo<=hi){
            while(lo<=hi && A[lo] == A[lo+1]) ++lo;
            while(lo<=hi && A[hi] == A[hi-1]) --hi;
            int mid = lo+(hi-lo)/2;
            if(A[mid] == target) return true;
            if(A[mid]>=A[lo]){
                if(target<=A[mid] && target>=A[lo]) hi = mid-1;
                else lo = mid+1;
            }else{
                if(target>=A[mid] && target<=A[hi]) lo = mid+1;
                else hi = mid-1;
            }
        }
        return false;
    }

你可能感兴趣的:(sorting)