題目:
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).
Code :
1 int search(const vector<int>& nums, int target) 2 { 3 int first = 0, last = nums.size(); 4 while (first != last) 5 { 6 const int mid = first + (last - first) / 2; 7 if (nums[mid] == target) 8 return mid; 9 //target value in the left 10 else if (nums[first] <= nums[mid]) 11 { 12 if (nums[first] <= target && target < nums[mid]) 13 last = mid; 14 else 15 first = mid + 1; 16 } 17 //target value in the right 18 else 19 { 20 if (nums[mid] < target && target <= nums[last - 1]) 21 first = mid + 1; 22 else 23 last = mid; 24 } 25 } 26 return -1; 27 }