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.

class Solution {
public:
    bool search(int A[], int n, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (n == 0) return false;
        
        int l = 0;
        int u = n-1;
        bool result = false;
        while(l <= u)
        {
            int mid = l+(u-l)/2;
            
            if (A[mid] == target)
                return true;
            else if (A[mid] > A[l])
            {
                if (A[l] <= target && target < A[mid])
                {
                    u = mid - 1;
                }
                else
                {
                    l = mid + 1;
                }
            }
            else if (A[mid] < A[l])
            {
                if (A[u] >= target && target > A[mid])
                {
                    l = mid + 1;
                }
                else
                {
                    u = mid - 1;
                }
            }
            else
            {
                if (A[mid] != A[u])
                {
                    l = mid + 1;
                }
                else
                {
                    result = search(A+l, mid-l,target);
                    if (!result)
                        result = search(A+mid+1, u-mid ,target);
                    break;
                }
            }
        }
        return result;
    }
};

你可能感兴趣的:(LeetCode: Search in Rotated Sorted Array II)