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
.
给定一个阵列 nums 他会旋转了 1 到 n 次,比如 [0,1,2,3,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] 如果它被旋转了 4 次,[0,1,2,4,5,6,7] 如果它被旋转了 7 次,虽然题目提到阵列会旋转但其实这只是陷阱,用 Binary Search 即可找到最小值。
Coding
/** * @param {number[]} nums * @return {number}*/var findMin = function(nums) { let l = 0, r = nums.length - 1; let min = Infinity; while (l <= r) { const mid = Math.floor((r - l) / 2) + l; min = Math.min(nums[mid], min); // min in right side if (nums[mid] > nums[r]) { l = mid + 1; } else { // min in left side r = mid - 1; } } return min;};
里用 l
和 r
指标指定阵列的两端并找到中间的值 mid
,如果 mid
的值大于 r
的值,代表最小值在 mid 的右边
,将 l
移动到 mid
右边一格再次找 l
跟 r
的 mid
,持续找到最小值。