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: 4Example 2:
Input: nums = [
4,5,6,7,0,1,2]
, target = 3
Output: -1
属于有序数组的搜索,用二分搜索就好
public int search(int[] nums, int target) {
int offset=0;
for(int i=1;i<nums.length;i++){
if(nums[i-1]>nums[i]){
offset=i;
break;
}
}
int left=0;
int right=nums.length-1;
while(right>=left){
int mid=(right+left)/2;
int index=mid+offset;
if(index>=nums.length) index-=nums.length;
if(nums[index]==target) return index;
else if(nums[index]<target) {
left=mid+1;
}else{
right=mid-1;
}
}
return -1;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。