首页 > 其他分享 >81. Search in Rotated Sorted Array II

81. Search in Rotated Sorted Array II

时间:2023-03-07 13:05:29浏览次数:40  
标签:Search target nums ## Rotated mid II int array

##题目
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;
        
    }
};

标签:Search,target,nums,##,Rotated,mid,II,int,array
From: https://blog.51cto.com/u_15996214/6105915

相关文章