问题描述
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.
思路分析
一个已经排序的数组,在某一个位置分成两段然后交换了顺序,要求在这个数组中找到指定的target,返回它的index,如果没有返回-1。
Find Min in Rotated Sort Array的进阶版,首先利用上次的方法二分找到最小值的index,根据min的位置去定我们要搜索的范围是在旋转点的前部分还是后部分。
然后用二分搜索,如果搜索结束没有返回值,就返回-1。
代码
class Solution {
public:
int search(vector<int>& nums, int target) {
if (nums.size() == 0)
return -1;
int min = findMin(nums);
int start = 0, end = nums.size() - 1;
if (min != 0){
target > nums[end]? end = min - 1 : start = min;
}
while (start <= end){
int mid = start + (end - start) / 2;
if (target == nums[mid])
return mid;
else if (target >= nums[mid])
start = mid + 1;
else
end = mid - 1;
}
return -1;
}
int findMin(vector<int>& nums) {
int start = 0, end = nums.size() - 1;
while (start < end){
if (nums[start] < nums[end])
return start;
int mid = start + (end - start) / 2;
if (nums[start] <= nums[mid])
start = mid + 1;
else
end = mid;
}
return start;
}
};
时间复杂度:
O(logn)
O
(
l
o
g
n
)
空间复杂度:
O(1)
O
(
1
)
反思
二分搜索的条件设置还是有些敏感的。循环终止条件,start和end的移动都有些意思的。