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.
class Solution {
public:
bool search(vector<int>& nums, int target) {
if(nums.size() == 0) return false;
int low = 0, high = nums.size()-1;
while(low<=high){
int mid = low + (high-low)/2;
if(nums[mid] == target) return true;
if(nums[mid] > nums[low]){
if(target < nums[mid] && target >= nums[low]){
high = mid - 1;
}else{
low = mid + 1;
}
}else if(nums[mid] < nums[low]){
if(target > nums[mid] && target <= nums[high]){
low = mid + 1;
}else{
high = mid - 1;
}
}else{
low++;
}
}
return false;
}
};
81. Search in Rotated Sorted Array II
最新推荐文章于 2023-11-12 22:36:10 发布