您的位置:首页 > 其它

Search in Rotated Sorted Array II 旋转数组二分查找 有重复

2015-04-20 18:49 393 查看


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:

    //1,1, 1,2,1,1,1,恰好左中右都是1,这时我们 ++左下标,--右下标
    bool search(int A[], int n, int target) {
        
        if(n==0)
            return false;
        int left,right,mid;
        left=0;
        right=n-1;
        while(left<=right)
        {
            mid=(left+right)/2;
            if(A[mid]==target)
                return true;
            if(A[left]==A[mid]&&A[mid]==A[right])
            {
                left++;right--;
            }
            else if(A[left]<=A[mid])//左边有序
            {
                if(A[left]<=target&&target<A[mid])
                    right=mid-1;
                else
                    left=mid+1;
            }
            else if(A[mid]<=A[right])
            {
                if(A[mid]<target&&target<=A[right])
                    left=mid+1;
                else
                    right=mid-1;
            }
        }
        return false;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐