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.
最基本的思路自然是逐个遍历,未曾想竟然也accept。。tag提示:binary search
//思路,因为数组原本有序,而rotate的效果也就是将数组A从某点分为前后两部分,再整体交换两部分。
//那么若将数组二分,肯定(至少)有一半是有序的。假设数组原为升序[小]-[大],那么rotate之后的效果:[大]-[小]。
//即只会在两个部分的交界处(pivot)发生逆序,且这个pivot点只有一个,要么在左半(则右半有序),要么在右(左半有序)。
//升序、无重复时,每次迭代:m = (l + r) /2
//若A[m] < A[r]:则m-r段一定是有序的
//若A[m] >= A[r]:则l-m段一定是有序的
public class Solution {
public int search(int[] nums, int target) {
int index = -1;
int left = 0;
int right = nums.length - 1;
while(left <= right){
int middle = (left+right) / 2;
if(nums[middle] == target){ //找到目标
index = middle;
break;
}
if(nums[middle] < nums[right]){ //说明m-r段一定是有序的
if(nums[middle]<target && target<=nums[right]){ //target位于m-r段
left = middle + 1;
}else{ //target不位于m-r段
right = middle - 1;
}
}else{ //说明l-m段一定是有序的
if(nums[left]<=target && target<nums[middle]){ //target位于l-m段
right = middle - 1;
}else{ //target不位于l-m段
left = middle + 1;
}
}
}
return index;
}
}