Search in Rotated Sorted Array
题目:Suppose a sorted array 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.
思路:
二分法的变形,每次变换一共是三种情况,找出中间值,相等时最理想的情况;
中间值大于最左边的数以及中间值在下面。
对于第二种情况,考虑是不是左边的左边,然后就是right减去1;
对于第三种情况,考虑最右边的右边,然后就是left加上1.
好题目!!!
代码:
class Solution { public: int search(vector<int>& nums, int target) { int left=0,right=nums.size()-1; while(left<=right){ int mid=(left+right)/2; if(nums[mid]==target) return mid; if(nums[mid]>=nums[left]){ //在左边 if(target>=nums[left]&&target<nums[mid]) right=mid-1; else left=mid+1; }else{ //在右边 if(target<=nums[right]&&nums[mid]<target) left=mid+1; else right=mid-1; } } return -1; } };