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.
题意:略。一个升序数组在某点旋转后会出现的情况
0 1 2 4 5 6 7
4 5 6 7 0 1 2
7 0 1 2 4 5 6
1 2 4 5 6 7 0
最直接的办法分情况考虑(好蠢好蠢的)
1.恰好等于nums[mid]
2.比nums[mid]小,出现左右两边都有可能,如果target比nums[l]大肯定在左边了就–r;else比target右边还小就在右边了,然后是和nums[l],nums[r]分别相等,直接返回,否则就返回-1
3.同上考虑
class Solution {
public:
int search(vector<int>& nums, int target) {
int l = 0, r = nums.size() - 1;
int mid;
while(l <= r){
mid = l + (r - l) / 2;
if(nums[mid] == target)
return mid;
else if(target < nums[mid]){
if(target == nums[l])
return l;
else if(target == nums[r])
return r;
else if(target > nums[l])
r = mid - 1;
else if(target < nums[r])
++l;
else
return -1;
} else if(target > nums[mid]){
if(target == nums[l])
return l;
else if(target == nums[r])
return r;
else if(target > nums[l])
--r;
else if(target < nums[r])
l = mid + 1;
else
return -1;
}
}
return -1;
}
};
根据题意可以得出,Array可以分为两种情况:右边递增或者左边递增。在每种情况下判断target的情况
class Solution {
public:
int search(vector<int>& nums, int target) {
int len = nums.size();
int l, r, m;
l = 0, r = len - 1;
while(l <= r){
m = (r + l) / 2;
if(target == nums[m])
return m;
else if(nums[r] >= nums[m]){
if(nums[m] < target && target < nums[r])
l = m + 1;
else if(nums[r] == target)
return r;
else
r = m - 1;
} else if(nums[l] <= nums[m]){
if(nums[l] < target && target < nums[m])
r = m - 1;
else if(nums[l] == target)
return l;
else
l = m + 1;
}
}
return -1;
}
};