159. Find Minimum in Rotated Sorted Array(二分法)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lighthear/article/details/79394274
Description

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

Find the minimum element.

 Notice

You may assume no duplicate exists in the array.

Example

Given [4, 5, 6, 7, 0, 1, 2] return 0

Solution

这道题也是经典二分法例题的变形,需要找到第一个下降的元素。图形化数据,相当于一个上升的直线,然后突然掉下来, 再次上升,但是比第一个元素小。target应取最后一个元素的值而不是第一个,因为想把它转换成第一个满足(或不满足)某一条件的问题,及OOXX的问题。如果取target为第一个元素,条件为 First Position <= target 的话,就变成了OXX...XOO...OO,若条件是 First Position < target,则单调增的数组就没有比第一个元素小的数了,得不到任何结果。因此  target 应为最后一个元素,条件是 First Position <= target。

Java

public class Solution {
    /**
     * @param nums: a rotated sorted array
     * @return: the minimum number in the array
     */
    public int findMin(int[] nums) {
        // write your code here
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int start = 0, end = nums.length - 1;
        //xxxx
        //     oooo
        int target = nums[nums.length - 1];
        
        // find the first element <= target
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] <= target) {
                end = mid;
            } else {
                start = mid;
            }
        }
        if (nums[start] <= target) {
            return nums[start];
        } else {
            return nums[end];
        }
    }
}

猜你喜欢

转载自blog.csdn.net/lighthear/article/details/79394274