Type:medium
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.
给定一个rotated sorted array,判断给定数值在不在这个数组中。
二分法。
bool search(vector<int>& nums, int target) {
int n = nums.size();
int left = 0;
int right = n-1;
sort(nums.begin(), nums.end());
while(left<=right){
int mid = left + (right - left)/2;
if(target == nums[mid]) return true;
else if(target < nums[mid]){
right = mid - 1;
}else{
left = mid + 1;
}
}
return false;
}