Thursday, October 17, 2013

Search in Rotated Sorted Array II [Leetcode]

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.

Solution: binary search again, but sometimes we may need to search both left and right sides since we have no idea about which side is sorted in the increasing order, like [2, 2, 2, 3, 2] .

class Solution {
public:
    bool searchHelper(int A[], int start, int end, int target){
        if(start>end)
            return false;
        int mid = (start+end)/2;
        if(A[mid]==target)
            return true;

        //the right part is sorted in the increasing order
        if(A[mid]<A[end]){ 
            if(A[mid]>target || A[end]<target)
                return searchHelper(A, start, mid-1, target);
            return searchHelper(A, mid+1, end, target);
        }
        //the left part is sorted in the increasing order
        if(A[mid]>A[end]){
            if(A[mid]<target || A[start]>target)
                return searchHelper(A, mid+1, end, target);
            return searchHelper(A, start, mid-1, target);
        }
        //do not know which part is sorted in the increasing order
        bool ret = searchHelper(A, start, mid-1, target);
        if(ret) 
            return true;
        else
            return searchHelper(A, mid+1, end, target);
    }
    bool search(int A[], int n, int target) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(n<=0) return false;
        return searchHelper(A, 0, n-1, target);
    }
};

No comments:

Post a Comment