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

leetcode 题解

搜索旋转排序数组-ag真人游戏

阅读 : 1309

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)时间,把问题的规模缩小一半。
旋转排序数组如下:

如果中间在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& 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;
    }
}
网站地图