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 of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1
思路:这道题还是挺简单的,因为旋转之后两部分的数还是有顺序的,左边部分的数据是升序,右边部分是降序排列,所以可以利用这个规律用头尾两个指针来查找。
代码:
class Solution {
public:
int search(vector<int>& nums, int target) {
int l = 0,r = nums.size()-1;
while(l<=r){
if(nums[l]==target) return l;
if(nums[r]==target) return r;
if(target>nums[l]) l++;
else if(target<nums[r]) r--;
else return -1;
}
return -1;
}
};
上面的思路错了,虽然这样可以求出结果,但是根本没有利用它有序和旋转后的特性。没旋转之前它是升序排列,旋转以后一部分是降序排列另一部分是升序排列。所以应该先判断出来哪边是升序,哪边是降序,判断目标值落在哪部分区域。
代码:
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0,right = nums.size()-1,mid;
while(left<=right){
mid = (left+right)/2;
if(nums[mid]==target) return mid;
if(nums[left]<=nums[mid]){
if(target>=nums[left]&&target<nums[mid]) right = mid-1;
else left = mid+1;
}
else{
if(target>nums[mid]&&target<=nums[right]) left = mid+1;
else right = mid-1;
}
}
return -1;
}
};