153. Find Minimum in Rotated Sorted Array(js)

153. Find Minimum 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]).

Find the minimum element.

You may assume no duplicate exists in the array.

Example 1:

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

Example 2:

Input: [4,5,6,7,0,1,2]
Output: 0
题意:给定一个旋转后的数组,返回最小项,不能暴力遍历,时间复杂度要求O(lgn)
代码如下:
/**
 * @param {number[]} nums
 * @return {number}
 */
var findMin = function(nums) {
    let left = 0,right=nums.length-1;
//     如果最后一项大于第一项,说明没有旋转,直接返回第一项,否则继续二分查找
    if(nums[left]>nums[right]){
//         最后会剩下相邻两项,较小的项即为最小项
        while(left+1!==right){
            let mid=parseInt((left+right)/2);
            if(nums[left]>nums[mid]) right=mid;
            else left=mid; 
        }
        return Math.min(nums[left],nums[right]);
    }
    return nums[0]
};

 

posted @ 2019-07-27 20:10  mingL  阅读(93)  评论(0编辑  收藏  举报