Search in Rotated Sorted Array II -- Leetcode

来源:互联网 发布:专业网络直播设备 编辑:程序博客网 时间:2024/06/06 01:18

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) {        int hi,low;        hi=n-1;        low=0;        while(low<=hi){            int mid=(low+hi)/2;            if(target==A[mid] || target==A[hi] || target==A[low])                return true;            if(A[low]<A[mid]){                if(A[low]<=target && target<A[mid])                    hi=mid-1;                else                    low=mid+1;            }            else if(A[low]>A[mid]){                if(A[mid]<target && target<=A[hi])                    low=mid+1;                else                    hi=mid-1;            }            else                low++;        }        return false;    }};

总结:

1. 此题需另外考虑duplicates的情况

2. 因为可能存在duplicate,当二分搜索中low<=mid时,不一定保证该区间是递增的,但low>mid时,仍可按照I时的做法做

3. 当low==mid时,说明存在duplicate,则要low++去消除duplicate

0 0
原创粉丝点击