Search in Rotated Sorted Array——LeetCode
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).
Example 1:
Input: nums = [4,5,6,7,0,1,2]
, target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2]
, target = 3
Output: -1
题目大意:有序数组旋转,寻找其中是否有某个特定的值,时间复杂度O(log n)。
思路:旋转后的数组,旋转后的后一部分肯定比前一部分所有元素都小;所以数组从中间分开,至少有一半是有序的。
那么可以得到,如果中间的元素(也就是nums[mid])比nums[0]大,那么前半部分有序,如果中间的元素比nums[len-1]小,那么后半部分有序,这两种情况只会出现一种。这样就可以先看这个数在不在有序的这一半数组中,在的话没什么好说的,二分查找;不在的话,继续找另一半RotatedArray。思路就是这么个思路,然而想把题目A掉还要考虑很多细节,尤其是边界值,> or >= ,< or <=等等,极易出错。
public int search(int[] nums, int target) { if (nums == null || nums.length == 0) { return -1; } int low = 0, high = nums.length - 1; while (low <= high) { int mid = (low + high) >> 1; if (nums[mid] == target) { return mid; } if (nums[low] <= nums[mid]) { if (target >= nums[low] && target <= nums[mid]) { high = mid - 1; } else { low = mid + 1; } } else { if (target >= nums[mid] && target <= nums[high]) { low = mid + 1; } else { high = mid - 1; } } } return -1; }