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
public int search(int[] nums, int target) {
boolean isBig = false;
if (nums.length == 0) {
return -1;
}
int boundary = nums[0];
if(target > boundary) {
isBig = true;
} else if(target == boundary) {
return 0;
}
int begin = 0, end = nums.length - 1;
int temp = 0;
for (; end >= begin;) {
temp = (begin + end) >> 1;
if (target > nums[temp]) {
if(isBig && boundary > nums[temp]) {
end = temp - 1;
} else {
begin = temp + 1;
}
} else if (target < nums[temp]) {
if(!isBig && nums[temp] >= boundary) {
begin = temp + 1;
} else {
end = temp - 1;
}
} else {
return temp;
}
}
return -1;
}
我的代码逻辑:
以第一个数4作为边界点数:
假设一个数组:
[4,5,6,7,0,1,2], 比4大的4-7叫做大串, 比4小的0-2叫做小串
由于效率原因,我们使用二分查找,其实就是不断缩小begin 和 end的过程,
1.当一个数大于4那就肯定在大串当中,注意一点, 什么时候开始缩小end呢,就是比如你要找7, 但是二分的值是0时,这个数比边界点数要小,说明就是缩小end了。
2.当一个数小于4那就肯定在小串当中,同理, 什么时候开始增加begin呢,就是比如你要找1, 但是二分的值是7时,这个数比边界点数要大,说明就是增加begin了。