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
tag : array, binary search
method 1 binary search
观察题目发现,因为数组被旋转了,所以可以确定,左边被旋转的那一部分的第一个数比右边被旋转的部分都大,右边被旋转的最后一个数也是比左边被旋转的所有数都小,所以每次二分查找时,判断mid的左边和右边是否正常,比较target和nums[start]的大小关系,如果nums[start] 比 target大,说明target应该位于mid的右边
public int search(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
while (start <= end){
int mid = (start + end) / 2;
if (nums[mid] == target)
return mid;
if (nums[start] <= nums[mid]){
if (target < nums[mid] && target >= nums[start])
end = mid - 1;
else
start = mid + 1;
}
if (nums[mid] <= nums[end]){
if (target > nums[mid] && target <= nums[end])
start = mid + 1;
else
end = mid - 1;
}
}
return -1;
}
summary
- 虽然数组被改变过,但部分还是有序的,所以仍然可以使用二分查找