Type:medium
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]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order ofO(logn).
Example 1:
Input:nums = [4,5,6,7,0,1,2], target = 0Output:4
Example 2:
Input:nums = [4,5,6,7,0,1,2], target = 3Output:-1
给定一个旋转有序数组,一个target值。在这个数组中寻找target,若能找到,返回它的位置,不能找到则返回-1。
采用二分法寻找target。已知在数组中,若中间值大于最右值,则中间值左面的数组是有序的;反之,若中间值小于最右值,则中间值右面的数组是有序的。通过这半边的有序数组,我们可以判断target值是否在这区间内,若在,则在这半边继续搜索;若不在,则在另半边继续搜索。
class Solution {
public:
int search(vector<int>& nums, int target) {
int n = nums.size();
int left = 0;
int right = n-1;
while(left<=right){
int mid = left + (right - left)/2;
if(nums[mid] == target) return mid;
else if(nums[mid] <= nums[right]){
if(nums[mid] < target && nums[right] >= target) left = mid + 1;
else right = mid - 1;
}else if(nums[mid] > nums[right]){
if(nums[left] <= target && nums[mid] > target) right = mid - 1;
else left = mid + 1;
}
}
return -1;
}
};
//二分法