题目
解法:二分查找
直接上leetcode官方解释吧,挺清楚的
python代码:
class Solution:
def search(self, nums: List[int], target: int) -> int:
start, end = 0, len(nums) - 1
while start <= end:
mid = start + (end - start) // 2
if nums[mid] == target:
return mid
elif nums[mid] >= nums[start]:
if target >= nums[start] and target < nums[mid]:
end = mid - 1
else:
start = mid + 1
else:
if target <= nums[end] and target > nums[mid]:
start = mid + 1
else:
end = mid - 1
return -1
C++版本
class Solution {
public:
int search(vector<int>& nums, int target) {
// the idea is to search which sorted part does the target fall into, once we found this, the rest is a regular binary search because part of the condition will be always true
// due to the special case of this problem, we need to check for the first and lst position
if(nums[0] == target){
return 0;
}
if(nums[nums.size() - 1] == target){
return nums.size() - 1;
}
int l = 0, r = nums.size()-1;
int mid;
while(l+1 < r){
mid = (r - l)/2 + l;
// if nums[mid] > nums[0], from position 0 to mid is sorted
if(nums[mid] > nums[0]){
// if nums[mid] > target and nums[0] < target, then the target falls into a sorted range from position 0 to mid, then in the continue process, "nums[0] < target" will be always valid, it shrink to a regular binary search process
if(nums[mid] > target && nums[0] < target){
r = mid;
// Otherwise, the target is in the unsorted mid to end, then we change the left and continue searching for sorted part
}else{
l = mid;
}
// if nums[mid] < nums[0], from position mid to end is sorted
}else{
// similarly, if nums[mid] < target and nums[end] > target, then the target falls into a sorted range from position mid to end, then in the continue process, "nums[end] > target" will be always valid, it shrink to a regular binary search process
if(nums[mid] < target && nums[nums.size() - 1] > target){
l = mid;
}else{
r = mid;
}
}
}
if(nums[l] == target){
return l;
}
if(nums[r] == target){
return r;
}
return -1;
}
};