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
Example2:
Input: nums = [ 4, 5, 6, 7, 0, 1, 2 ], target = 3
Output: -1
这道题还是二分法,但是有6种情况,最本来的二分法是只用计算middle的值匹不匹配即可以,但是因为我们判断的条件不单单有middle,还有nums[begin], 所以判断的时候要判断两个(至少我是这么做的)。
int search(vector<int>& nums, int target) {
int begin = 0, end = nums.size() - 1;
int res = -1;
while(begin <= end){
int middle = (begin + end)/2;
int firstNum = nums[begin];
int middleNum = nums[middle];
if(middleNum == target){
res = middle;
break;
}
if(target == nums[begin]){
res = begin;
break;
}
if(firstNum <= middleNum){
if(target < firstNum || target > middleNum)
begin = middle + 1;
else
end = middle -1;
}
if(firstNum > middleNum){
if(target > firstNum || target < middleNum)
end = middle - 1;
else
begin = middle + 1;
}
}
return res;
}
但是!讨论区的大牛就是还是用的一个判断条件,我觉得很厉害啊,反正我是写不出这种代码的:(虽然本质上解题思路还是一样的,但是人家的异或真的用的好厉害啊,嗷嗷我什么时候才可以这么厉害啊QAQ)
int search(vector<int>& nums, int target) {
int lo = 0, hi = int(nums.size()) - 1;
while (lo < hi) {
int mid = (lo + hi) / 2;
if ((nums[0] > target) ^ (nums[0] > nums[mid]) ^ (target > nums[mid]))
lo = mid + 1;
else
hi = mid;
}
return lo == hi && nums[lo] == target ? lo : -1;
}
Example 2: