2014年10月26日星期日

[Leetcode] Search in Rotated Sorted Array II

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.
The key point is the same with here, try to identify the monotonic part of the array. However, since we have duplicate in array now, we may have the situation that A[mid] is the same with current interval's left-most and right-most element. In such case, we just need to shrink the interval by one, and continue on this new interval.
    public boolean search(int[] A, int target) {
        int n = A.length;
        if(n == 0)
            return false;
        int l = 0, r = n-1;
        while(l <= r) {
            int mid = l + (r-l)/2;
            if(A[mid] == target)
                return true;
            if(A[mid] == A[l]) {
                l++; continue;
            }
            if(A[mid] == A[r]) {
                r--; continue;
            }
            if(A[mid] > A[l]) {
                if(target >= A[l] && target < A[mid])
                    r = mid - 1;
                else
                    l = mid + 1;
            }
            else if(A[mid] < A[r]) {
                if(target <= A[r] && target > A[mid])
                    l = mid + 1;
                else
                    r = mid - 1;
            }
        }
        return false;
    }

没有评论:

发表评论