LeetCode:Search in Rotated Sorted Array
Problem:
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.
二分查找变形
1 class Solution { 2 public: 3 int search(vector<int>& nums, int target) { 4 int first=0; 5 int last=nums.size(); 6 7 while(first!=last) 8 { 9 10 int middle=(first+last)/2; 11 if(nums[middle]==target) 12 return middle; 13 else 14 if(nums[first]<=nums[middle]) 15 { 16 if(nums[first]<=target&&target<=nums[middle]) 17 last=middle; 18 else 19 first=middle+1; 20 } 21 else 22 { 23 if(nums[middle]<target&&target<=nums[last-1]) 24 first=middle+1; 25 else 26 last=middle; 27 } 28 } 29 30 return -1; 31 } 32 };