33. Search in Rotated Sorted Array
题目
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).
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
Example
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
解法
暴力搜索时间复杂度不满足要求,所以使用二分
- 使用二分法,如果nums[left] <= nums[mid]则左边是递增序列,反之右边是递增序列
- 若target在递增序列内,则在递增序列内继续二分;反之在另一半里二分
代码
public int search(int[] nums, int target) {
int res = -1;
int left = 0, right = nums.length-1;
while(left <= right) {
int mid = (left + right) / 2;
if(target == nums[mid]) {
res = mid;
break;
}
else if(nums[left] <= nums[mid]) {
if(nums[left] <= target && target < nums[mid])
right = mid-1;
else
left = mid+1;
}
else {
if(nums[mid] < target && target <= nums[right])
left = mid+1;
else
right = mid-1;
}
}
return res;
}
执行用时 : 14 ms, 在Search in Rotated Sorted Array的Java提交中击败了69.62% 的用户
内存消耗 : 39.9 MB, 在Search in Rotated Sorted Array的Java提交中击败了0.89% 的用户