[LeetCode 解题报告]033. Search in Rotated Sorted Array

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

考察:二分查找,首先我们数组nums=[0,1,2,4,5,6,7]的所有旋转情况,如下:

  • 0,1, 2,4,5,6,7
  • 1,2,4,5,6,7,0
  • 2,4,5,6,7,0,1
  • 4,5,6,7,0,1,2
  • 5,6,7,0,1,2,4
  • 6,7,0,1,2,4,5
  • 7,0,1,2,4,5,6

可以发现,无论怎样的旋转,要么前半段有序,要么后半段有序;那么怎么判断是前半段有序还是后半段有序呢。

  • nums[mid] < nums[right] 后半段有序
  • nums[left] < nums[mid] 前半段有序
class Solution {
public:
    int search(vector<int>& nums, int target) {
        if (nums.size() < 1 || (nums.size() == 1 && nums[0] != target))
            return -1;
        int left = 0, right = nums.size()-1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target)
                return mid;
            else if (nums[mid] < nums[right]) { //后半段有序
                if (nums[mid] < target && nums[right] >= target)
                    left = mid + 1;
                else
                    right = mid - 1;
            }
            else { // 前半段有序
                if (nums[left] <= target && target < nums[mid])
                    right = mid - 1;
                else
                    left = mid + 1;
            }
        }
        return -1;
    }
};

完, 

上一篇:0081. Search in Rotated Sorted Array II (M)


下一篇:788. Rotated Digits*