Suppose a sorted array 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.
这个题目用暴力搜索也能一次过,不过时间复杂度太高。
看tag有二分查找就按照二分查找写,总是有错误。最后看了下别人的代码,将mid =( start + last) / 2 改为 mid =( start + last +1) / 2 之后就通过了,至于问题出在哪里我也不是太清楚。
Java实现如下:
public class Solution {
public int search(int[] nums, int target) {
if(nums == null)
return -1;
for(int start = 0,last = nums.length -1;start <= last ; ){
int middle = (start + last +1)/2;
if(target == nums[middle])
return middle;
if(nums[middle] > nums[start]){
if(target < nums[middle] && target >= nums[start])
last = middle -1;
else
start = middle +1;
}
else{
if(target > nums[middle] && target <= nums[last])
start = middle +1;
else
last = middle -1;
}
}
return -1;
}
}