1、题目描述
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
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
2、问题描述:
- 就是将一个排好序的数组,将后面一部分移到前面来,给一个target找target的位置。
3、问题关键:
- 有序:二分法。
- 判断是否具有翻转。
- 有翻转的性质可知,如果翻转了nums[0] > nums.back();
- 找到中间的位置,判断target在哪一边,再使用一次二分。
4、C++代码:
class Solution {
public:
int search(vector<int>& nums, int target) {
if (nums.empty()) return -1;//LeetCode常见套路,判断是否为空。
if (nums.size() < 5) //如果数组的长度比较小,直接遍历。这个可以不做。
{
for (int i = 0 ; i < nums.size(); i ++)
{
if (nums[i] == target) return i;
}
return -1;
}
int left = 0, right = nums.size() - 1;
if (nums[0] > nums.back() ) //判断是否具有翻转,如果翻转了找到转折点。
{
int l = 0, r = nums.size() - 1;
while( l < r)
{
int mid = l + r + 1 >> 1;
if (nums[mid] >= nums[0]) l = mid;//l = mid,所以mid = l + r + 1;
else r = mid - 1;
}
if ( target >= nums[0]) left = 0, right = l;//如果target >= nums[0], 说明在前一半。
else left = l + 1, right = nums.size() - 1;
}
while (left < right )//在前一段或者后一段二分查找目标值。
{
int mid = left + right >> 1;
if (nums[mid] < target) left = mid + 1;//left = mid + 1, 所以mid = left + right 。
else right = mid;
}
if (nums[left] == target) return left;
return -1;
}
};