LeetCode Java First 400 题解-033

Search in Rotated Sorted Array    Medium

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.

public int search(int[] A, int target) {

    int lo = 0;

    int hi = A.length - 1;

    if (hi < 0)

        return -1;

    while (lo < hi) {

        int mid = (lo + hi) / 2;

        if (A[mid] == target)

            return mid;

        if (A[lo] <= A[mid]) {

            if (target >= A[lo] && target < A[mid])

                hi = mid - 1;

            else

                lo = mid + 1;

        } else {

            if (target > A[mid] && target <= A[hi])

                lo = mid + 1;

            else

                hi = mid - 1;

        }

    }

    return A[lo] == target ? lo : -1;

}

思路:二分查找其实并不需要整个数组有序,其中有一半有序即可。一个变形的二分查找,判断条件:先和0点比,可以判断是怎么Rotate的,然后再判断应该落在哪个区间。O(lgn)

你可能感兴趣的:(刷题)