33. 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.

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

 

用binary search,循环终止条件是 l + 1 >= r(这样的话最后需要判断一下l 和 r 位置元素是否等于target)

由于数组旋转过,由两部分递增的序列组成。首先判断l 和 m 所在元素的大小关系,如果[l, m]是递增序列,进一步判断target是否在该范围中,并用binary search查找target;如果nums[l] > nums[m],说明[l, m)不是递增序列,而[m, r]是递增序列,进一步判断target是否在该范围中,并用binary search查找target。

时间:O(logN),空间:O(1)

class Solution {
    public int search(int[] nums, int target) {
        if(nums == null || nums.length == 0) return -1;
        int l = 0, r = nums.length - 1;
        
        while(l + 1 < r) {
            int m = l + (r - l) / 2;
            if(nums[m] == target)
                return m;
            if(nums[l] < nums[m]) {
                if(nums[l] <= target && target <= nums[m])
                    r = m;
                else
                    l = m;
            }
            else {
                if(nums[m] <= target && target <= nums[r])
                    l = m;
                else
                    r = m;
            }
        }
        if(nums[l] == target) return l;
        if(nums[r] == target) return r;
        return -1;
    }
}

 

posted @ 2018-12-04 11:47  fatttcat  阅读(117)  评论(0编辑  收藏  举报