菜鸟笔记
提升您的技术认知

Leetcode 题解

搜索旋转排序数组

阅读 : 3796

Problem
Suppose a sorted array 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 itsindex, otherwise return -1.

You may assume no duplicate exists in the array.

Example
For [4, 5, 0, 1, 2, 3] and target=1, return 3.

For [4, 5, 0, 1, 2, 3] and target=6, return -1.

Challenge
O(logN) time

题解 – 找到有序数组

对于有序数组,使用二分搜索比较方便。分析题中的数组特点,旋转后初看是乱序数组,但仔细一看其实里面是存在两段有序数组的。刚开始做这道题时可能会去比较target和A[mid], 但分析起来异常复杂。

该题较为巧妙的地方在于如何找出旋转数组中的局部有序数组,并使用二分搜索解之。

二分查找,难道主要在于左右边界的确定。

实现分析:

二分法的精髓是,用常数O(1)时间,把问题的规模缩小一半。
旋转排序数组如下:

Search in Rotated Sorted Array

如果中间在a处:mid >= nums[0]
——–|———-|———
nums[0] mid

  • target > mid or target < nums[0], 丢弃a的左边
  • nums[0] <= target < mid, 丢弃a的右边

如果中间在b处: mid < nums[0]
——–|———-|———
mid nums[0]

  • target < mid or target >= nums[0], 丢掉b的右边
  • mid < target <= nums[0], 丢弃b的左边

c++代码:

class Solution {
public:
    int search(const vector<int>& nums,int target) {
        int first = 0, last = num.size();
            while (first != last) {
                const int mid = first + (last - first) / 2;
                if (nums[mid] == target) {
                    return mid;
                }
                if (nums[first] < nums[mid]) {
                    if (nums[first] <= target) && target < nums[mid]) {
                        last = mid;
                     } else {
                        first = mid + 1;
                     }
                } else {
                    if (nums[mid] < target && target <= nums[last-1]) {
                        first = mid + 1;
                    } else {
                        last = mid;
                    }
                }
            }
            return -1;
        }
};

java代码:

public class Solution {
    /**
     *@param A : an integer rotated sorted array
     *@param target :  an integer to be searched
     *return : an integer
     */
    public int search(int[] A, int target) {
        if (A == null || A.length == 0) return -1;

        int lb = 0, ub = A.length - 1;
        while (lb + 1 < ub) {
            int mid = lb + (ub - lb) / 2;
            if (A[mid] == target) return mid;

            if (A[mid] > A[lb]) {
                // case1: numbers between lb and mid are sorted
                if (A[lb] <= target && target <= A[mid]) {
                    ub = mid;
                } else {
                    lb = mid;
                }
            } else {
                // case2: numbers between mid and ub are sorted
                if (A[mid] <= target && target <= A[ub]) {
                    lb = mid;
                } else {
                    ub = mid;
                }
            }
        }

        if (A[lb] == target) {
            return lb;
        } else if (A[ub] == target) {
            return ub;
        }
        return -1;
    }
}