Description:
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);
解法:题目要求时间复杂度在O(log n),那么我们就不可能通过遍历一遍数组来找到这个元素,可以通过二分查找法来搜索,但是,现在的数组可能在任意一个地方发生旋转,导致整个数组时无序的;虽然数组被旋转了,数组中被旋转的两个部分仍然是有序的;对于数组[0,1,2,4,5,6,7]来说,一共有以下几种旋转方案:
1 2 4 5 6 7 0
2 4 5 6 7 0 1
4 5 6 7 0 1 2
5 6 7 0 1 2 4
6 7 0 1 2 4 5
7 0 1 2 4 5 6
0 1 2 4 5 6 7
- if nums[mid] > nums[right] : 左边的序列是有序的
- if nums[mid] < nums[right] : 右边的序列是有序的
无论哪一种情况,我们只需要判断目标元素是否在有序的那部分值的范围中,若不在,那必定是在另外一个部分;
class Solution {
public int search(int[] nums, int target) {
if(nums.length == 0){
return -1;
}
int left = 0;
int right = nums.length - 1;
int mid = (left + right) / 2;
while(left <= right){
if(nums[mid] == target){
return mid;
}
else if(nums[mid] > nums[right]){
if(target >= nums[left] && target < nums[mid]) right = mid - 1;
else left = mid + 1;
}//ordered int the left half
else{
if(target > nums[mid] && target <= nums[right]) left = mid + 1;
else right = mid - 1;
}//ordered in the right half
mid = (left + right) / 2;
}
return -1;
}
}