81. Search in Rotated Sorted Array II

来源:互联网 发布:西安爱知 地址 编辑:程序博客网 时间:2024/06/10 00:07

题目

Follow up for “Search in Rotated Sorted Array”:
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Write a function to determine if a given target is in the array.

The array may contain duplicates.

思路

这道题目,如果仅仅是实现,是很简单的,最坏情况O(n),我们知道在有序数组的情况下,二分搜索的时间复杂度是O(logn),那么在存在反转的情况下,能否使用二分搜索呢?答案是肯定的,唯一的区别就是三个索引值确定需要修改:left,right,mid

代码

class Solution {public:    bool search(vector<int>& nums, int target) {        if(nums.empty())            return false;        int l=0,r=nums.size()-1;        int mid = 0;        while(l<r)        {            mid = (l+r)/2;            if(nums[mid]==target)//如果相等                return true;            if(nums[mid]>nums[r])//如果大于            {                if(nums[mid]>target&&nums[l]<=target)                    r=mid-1;                else                    l=mid+1;            }            else if(nums[mid]<nums[r])//如果小于            {                if(nums[mid]<target&&nums[r]>=target)                    l=mid+1;                else                    r=mid-1;            }            else //如果等于                r--;        }        return nums[l]==target?true:false;    }};
原创粉丝点击