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.

Solution:Binary Search

Example: [7 8 9 0 1 2 3 4 5 6]
思路: Binary Search 在mid处 二分parts,若A[lo] <= A[mid],则可知左边正常增序,则右边part含有rotated部分,vice versa。二分确定好parts后,来判断target是在哪个part中就可以继续二分查找(通过正常这边的前后范围判断,else则在rotated那边)。循环此过程直到在A[mid]找到target或! lo < hi。
Time Complexity: O(logN) Space Complexity: O(1)

Solution Code:

class Solution {
    public int search(int[] A, int target) {
        if(A == null || A.length == 0) return -1;
        
        int lo = 0, hi = A.length - 1;
        while (lo <= hi) {
            int mid = (lo + hi) / 2;
            if (A[mid] == target) return mid;

            if (A[mid] >= A[lo]) {
                // rotated part is in the right
                if (target >= A[lo] && target < A[mid]) {
                    // target is in the left
                    hi = mid - 1;
                } else {
                    // target is in the right
                    lo = mid + 1;
                }
            } else {
                // rotated part is on the left
                if (target > A[mid] && target <= A[hi]) {
                    // target is in the right
                    lo = mid + 1;
                } else {
                    // target is in the left
                    hi = mid - 1;
                }
            }
        }
        return -1;
    }
}

你可能感兴趣的:(33. Search in Rotated Sorted Array)