【Leetcode】【Hard】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.
解题:
二分搜索的应用,可以有两种思路:
(1)将数列从mid处划分,按照前半段序列顺序正常,或者不正常,进行条件判断,达到log(n)的二分效果;
(2)将数列从mid处划分,比较mid处元素和target,按照mid元素大,或者mid元素小,进行条件判断,达到log(n)的二分效果;
代码实现1:
代码简介,灵活的运用的二分的思想,将正常/非正常作为二分标准,而不是mid值大还是小。
1 class Solution { 2 public: 3 int search(vector<int>& nums, int target) { 4 int start = 0; 5 int end = nums.size() - 1; 6 while (start <= end) { 7 int mid = (start + end) / 2; 8 if (nums[mid] == target) 9 return mid; 10 if (nums[start] <= nums[mid]) { 11 if (nums[start] <= target && target <= nums[mid]) 12 end = mid - 1; 13 else 14 start = mid + 1; 15 } else { 16 if (nums[mid] <= target && target <= nums[end]) 17 start = mid + 1; 18 else 19 end = mid - 1; 20 } 21 } 22 23 return -1; 24 } 25 };
代码实现2:
思路更常规,虽然代码不如1简介,但是逻辑更好理解。
1 class Solution { 2 public: 3 int search(vector<int>& nums, int target) { 4 int left = 0; 5 int right = nums.size() - 1; 6 while (left < right) { 7 int mid = (left + right) / 2; 8 if (nums[mid] > target) { 9 if (nums[left] <= target || nums[left] > nums[mid]) 10 right = mid; 11 else 12 left = mid + 1; 13 } else if (nums[mid] == target) { 14 left = mid; 15 break; 16 } else { 17 if (nums[right] >= target || nums[mid] > nums[right]) 18 left = mid + 1; 19 else 20 right = mid; 21 } 22 } 23 24 if (nums[left] == target) 25 return left; 26 else 27 return -1; 28 } 29 };