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),那么首先想到的就是二分法。
因为不知道旋转的中心点在哪,所以需要分情况讨论。
整体思路可以分为两个部分:
if (nums[mid] >= nums[right])
以数组 [4, 5, 6, 7, 8, 9, 0, 1, 2] 为例
4 5 6 7 8 9 0 1 2
↑ ↑ ↑
left mid right
↑ ↑
① target ② target
如果 target 的值位于左侧①,即 if(target>=nums[left]&&target
if(nums[mid] <= nums[right])
以数组 [7, 8, 9, 0, 1, 2, 4, 5, 6] 为例
7 8 9 0 1 2 4 5 6
↑ ↑ ↑
left mid right
↑ ↑
① target ② target
如果 target 的值位于右侧②,即 if(target>nums[mid]&&target<=nums[right]),则移动左指针 left=mid+1
如果 target 的值位于左侧①,则移动右指针 right=mid-1
class Solution {
public int search(int[] nums, int target) {
if(nums == null) {
return -1;
}
int left = 0;
int right = nums.length-1;
while(left <= right) {
int mid = (left+right)/2;
if(nums[mid] == target) {
return mid;
}
if(nums[mid] >= nums[right]) {
if(target >=nums[left] && target < nums[mid]) {
right = mid-1;
} else {
left = mid +1;
}
}
if(nums[mid] <= nums[right]) {
if(target > nums[mid] && target <= nums[right]) {
left = mid+1;
} else {
right = mid-1;
}
}
}
return -1;
}
}