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.

class Solution {

public:

    bool search(int A[], int n, int target) {

        if(A==NULL||n==0)return false;

        int left=0, right=n-1;

        int mid;

        while(left<=right)

        {

            mid=(left+right)/2;

            if(A[mid]==target)return true;

            if (A[mid]==A[left]&&A[mid]==A[right])

            {

                left++;

                right--;

            }

            else if(A[mid]>=A[left])

            {

                if(A[mid]<target)left=mid+1;

                else

                {

                    if(target>=A[left])right=mid-1;

                    else left=mid+1;

                }

            }

            else

            {

                if(target<A[mid])right=mid-1;

                else 

                {

                    if (target<=A[right])left=mid+1;

                    else right=mid-1;

                }

            }

        }

        return false;

    }

};

 

你可能感兴趣的:(LeetCode)