You are given an integer array nums sorted in ascending order, and an integer target.
Suppose that nums 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]).
If target is found in the array return its index, otherwise, return -1.
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
Example 3:
Input: nums = [1], target = 0
Output: -1
Constraints:
1 <= nums.length <= 5000
-10^4 <= nums[i] <= 10^4
All values of nums are unique.
nums is guranteed to be rotated at some pivot.
-10^4 <= target <= 10^4
链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array
解题思路:
采用二分查找寻找value为target的元素。
因为,数组是递增顺序,可以以某个pivot进行旋转,旋转后的两个子数组也分别是递增的序列。
所以,采用二分法查找时,如果nums[mid] == target,则说明找到了,就返回下标index。
否则,比较nums[first]和nums[mid]的大小,如果nums[first] <= nums[mid],说明从first到mid是递增序列,如果target的值,刚好在这个递增序列内,last = mid,否则target如果不在这个递增序列内,就说明first的值要更新了,first = mid + 1。
如果nums[first] > nums[mid],就说明first到mid并不是一个递增序列,它肯定是旋转后的两个序列的交叉情况,这时候,从nums[mid]到nums[last-1]就是递增序列,判断,如果target在这个序列内,则first = mid+1,否则更新last = mid即可。
class Solution {
public:
int search(vector<int>& nums, int target) {
int first = 0;
int last = nums.size();
while(first < last)
{
const int mid = first + (last - first) / 2;
if(nums[mid] == target)
{
return mid;
}
if(nums[first] <= nums[mid])
{
if(target >= nums[first] && target < nums[mid])
{
last = mid;
}
else
{
first = mid + 1;
}
}
else
{
if(target > nums[mid] && target <= nums[last-1])
{
first = mid + 1;
}
else
{
last = mid;
}
}
}
return -1;
}
};