Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6]
might become [2,5,6,0,0,1,2]
).
You are given a target value to search. If found in the array return true
, otherwise return false
.
Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0 Output: true
Example 2:
Input: nums = [2,5,6,0,0,1,2], target = 3 Output: false
还是一个二分查找的问题,比起之前Search in Rotated Sorted Array这题,主要是多了左右相等的情况。
class Solution {
public:
bool search(vector<int>& nums, int target) {
if(nums.empty()) return false;
int n=nums.size(),l=0,r=nums.size()-1,m=(r+l)/2;
while(r>=l)
{
m=(l+r)/2;
if(nums[m]==target) return true;
if(nums[l]==nums[r])
{
if(nums[l]==target) return true;
l++;
r--;
continue;
}
if(nums[r]>=nums[m])
{
if(target>nums[m]&&target<=nums[r])
{
l=m+1;
}
else
{
r=m-1;
}
}
else
{
if(target>=nums[l]&&target<nums[m])
{
r=m-1;
}
else
{
l=m+1;
}
}
}
return false;
}
};