标签:
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.
分析:用二分查找法。mid = (low + high) / 2。考虑如下两种情形:
1. 如果nums[low] <= nums[mid]表示这一段区间是递增的,倘若target的值在两者之间,那么确定上界为mid - 1,否则下界为mid + 1;
2. 如果nums[low] > nums[mid]表示mid在最大值之后(举例: [4, 5, 6,0, 1, 2, 3]。数字0在6之后)如果target在nums[mid]和nums[high]之间,则可确定下界为mid + 1;否则上界为mid - 1。
运行时间7ms
1 class Solution { 2 public: 3 int search(vector<int>& nums, int target) { 4 if(nums.size() == 0) return -1; 5 if(nums.size() == 1){ 6 if(nums[0] == target) return 0; 7 else return -1; 8 } 9 10 int low = 0, high = nums.size()-1; 11 while(low <= high){ 12 int mid = (low + high) / 2; 13 if(nums[mid] == target) return mid; 14 if(nums[low] <= nums[mid]){ 15 if(nums[low] <= target && target < nums[mid]) high = mid; 16 else low = mid + 1; 17 } 18 else{ 19 if(nums[mid] < target && target <= nums[high]) low = mid + 1; 20 else high = mid; 21 } 22 } 23 return -1; 24 } 25 };
Search in Rotated Sorted Array
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/4466325.html