LeetCode 33. 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
解析:在旋转数组中查找目标值。首先来看旋转数组定义:将一个已经排好序的数组按照某一个轴进行旋转。比如原始数组为 0,1,2,4,5,6,7,如果按照2和4之间的轴进行旋转可以得到 4,5,6,7,0,1,2,同一个有序数组可以得到多种数组,比如以下几种:
0  1  2   4  5  6  7

7  0  1   2  4  5  6

6  7  0   1  2  4  5

5  6  7   0  1  2  4

4  5  6  7  0  1  2

2  4  5  6  7  0  1

1  2  4  5  6  7  0
其中粗体表示半边有序,可以发现不管怎么旋转,至少有半边是有序的,利用有序的信息并且限制的时间复杂度,采用二分查找的方式,每次在有序的部分进行二分查找。如果中间的数小于最右边的数,则右半边是有序的;如果中间的数大于最右边的数,则左半边是有序的。
代码如下:

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int low = 0, high = nums.size()-1;
        while(low <= high)
        {
            int mid = low + (high-low)/2;
            if(nums[mid] == target)
                return mid;
            if(nums[mid] < nums[high])//右半边有序
            {
                if(nums[mid] < target && nums[high] >= target)
                    low = mid + 1;
                else
                    high = mid -1;
            }else
            {
                if(nums[mid] > target && nums[low] <= target)
                    high = mid -1;
                else
                    low = mid +1;
            }
        }
        return -1;
    }
};
One Comment

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据