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
想法:发现此旋转数组在某个数字前后是顺序排列的,所以我们采用二分查找的方法。
其思想是,当旋转数组时,必须有一半数组仍按排序顺序排列。 例如,6 7 1 2 3 4 5,顺序从7到1之间的点中断。所以在进行二进制搜索时,我们可以判断哪个部分是有序的,目标是否在这个范围内,如果是的话,继续在这个范围内搜索,如果不是,继续在另一个范围内搜索。
注意:start可能=end target有可能等于 num[start]获nums[end] 要考虑到全体的情况 还有查找的大条件是while循环。
class Solution {
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(nums[start]<=target && nums[mid]>target)
end = mid-1;
else
start=mid+1;
}
if(nums[mid]<=nums[end]){
if(nums[mid]<target && nums[end]>=target)
start = mid+1;
else
end=mid-1;
}
}
return -1;
}
}