154. Find Minimum in Rotated Sorted Array II(js)

154. Find Minimum in Rotated Sorted Array II

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

Find the minimum element.

The array may contain duplicates.

Example 1:

Input: [1,3,5]
Output: 1

Example 2:

Input: [2,2,2,0,1]
Output: 0

Note:

题意:给定一个“旋转”的有序(从小到大排序)数组,找出其中最小值

代码如下:

/**
 * @param {number[]} nums
 * @return {number}
 */
// 二分查找:将数组看成两个非递减的子数组,所以最小值一定在第二个子数组的第一个,只要数组旋转了最小值就处于相对“右边”
// 即不断的比较中间值和“右侧值”就能找到最小值
var findMin = function(nums) {
    let left=0;
    let right=nums.length-1;
    while(left<right){
        let mid=Number.parseInt((left+right)/2);
        if(nums[right]>nums[mid]) right=mid;
        else if(nums[right]<nums[mid]) left=mid+1;
        // 如果元素值相等,较小的一定在right的左边,所以right向左移一位继续比较
        else right--;
    }
    return nums[left]
};

 

posted @ 2019-08-03 21:52  mingL  阅读(92)  评论(0编辑  收藏  举报