β

Search in Rotated Sorted Array

Michael's Blog 41 阅读

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.

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

Hope this helps,
Michael

作者:Michael's Blog
Thoughts, stories and ideas.
原文地址:Search in Rotated Sorted Array, 感谢原作者分享。

发表评论