题目: 发现循环数组中的最小值
类别:二分法+循环数组;
- Find Minimum in Rotated Sorted Array
Medium
10.4K
474
Companies
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:
[4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], …, a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], …, a[n-2]].
Given the sorted rotated array nums of unique elements, return the minimum element of this array.
You must write an algorithm that runs in O(log n) time.
Example 1:
Input: nums = [3,4,5,1,2]
Output: 1
Explanation: The original array was [1,2,3,4,5] rotated 3 times.
类型:简单二分+循环数组
一:建一个min=nums[0] 来返回和比较最小数;
二:先判断哪边是是有序数组;有序数组容易判断出最小值,循环数组,则不断二分,用mid比较
/**
* @param {number[]} nums
* @return {number}
*/
var findMin = function(nums) {
let left=0;
let right=nums.length-1;
let min=nums[0];
while(left<=right){
let mid=Math.floor(left+(right-left)/2);
if(nums[mid]>=nums[right]){ //一:先判断哪边是有序,哪边是循环,即右边是循环数组
min=Math.min(min,nums[left]);
left=mid+1;
}
else{
min=Math.min(min,nums[mid]); //即左边为循环数组;
right=mid-1;
}
}
return min;
};