题目:
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.
题解:
Solution 1
class Solution { public: int search(vector<int>& nums, int target) { int n = nums.size(); if(n < 1) return -1; int begin = 0, end = n; while(begin < end){ int mid = begin + (end - begin) / 2; if(nums[mid] == target) return mid; if(nums[begin] <= nums[mid]){ if(nums[begin] <= target && target < nums[mid]) end = mid; else begin = mid + 1; } else { if(nums[mid] < target && target <= nums[end - 1]) begin = mid + 1; else end = mid; } } return -1; } };
Solution 2
class Solution { public: int search(vector<int>& nums, int target) { int n = nums.size(); if(n < 1) return -1; int begin = 0, end = n - 1; while(begin < end){ int mid = begin + (end - begin) / 2; if(nums[mid] > nums[end]) begin = mid + 1; else end = mid; } int pivot = begin; begin = 0, end = n - 1; while(begin <= end){ int mid = begin + (end - begin) / 2; int realmid = (mid + pivot) % n; if(nums[realmid] == target) return realmid; else if(nums[realmid] < target) begin = mid + 1; else end = mid - 1; } return -1; } };