leetcode刷题系列C++-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.

Subscribe to see which companies asked this question

class Solution {
public:
    bool search(vector<int>& nums, int target) {
        int first = 0;
        int last = nums.size();
        int middle = 0;
        while(first != last)
        {
            middle = first + (last - first) / 2;
            if(nums[middle] == target)
            {
                return true;
            }
            if(nums[first] < nums[middle])
            {
                if(nums[first] <= target && target < nums[middle])
                {
                    last = middle;
                }
                else
                {
                    first = middle + 1;
                }
            }
            else if(nums[first] > nums[middle])
            {
                if(nums[middle] < target && target <= nums[last - 1])
                {
                    first = middle + 1;
                }
                else
                {
                    last = middle;
                }
            }
            else
            {
                first++;
            }
        }
        return false;
    }
};
出现11131这种的时候  会发现first和last是相等的  此时就无法来通过first last和middle来确定middle的区间了,因此这个地方只需要增加一个first++就可以了

你可能感兴趣的:(leetcode刷题系列C++-Search in Rotated Sorted Array II)