Friday, January 9, 2015

LeetCode 81: 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.
public class Solution {
    public boolean search(int[] A, int target) {
        // Adopt modified binary search
        int n = A.length;
        int lo = 0, hi = n-1;
        
        return rank(A, lo, hi, target);
    }
    
    private boolean rank(int[] A, int lo, int hi, int target)
    {
        if (hi < lo)
            return false;        
        
        int mid = (lo+hi)/2;
            
        if (A[mid] == target)
            return true;
            
        if (A[mid] > A[lo])
        {
            if (target>=A[lo] && target<A[mid])
                return rank(A, lo, mid-1, target);
            else
                return rank(A, mid+1, hi, target);
        }
        else if (A[mid] < A[lo])
        {
            if (target>A[mid] && target<=A[hi])
                return rank(A, mid+1, hi, target);
            else
                return rank(A, lo, mid-1, target);
        }
        else
        {
            if (A[mid] != A[hi])
                return rank(A, mid+1, hi, target);
            else
            {
                if (rank(A, lo, mid-1, target))
                    return true;
                else
                    return rank(A, mid+1, hi, target);
            }
        }
    }
}

No comments:

Post a Comment