[leetcode - Bliend-75 ] 153. Find Minimum in Rotated Sorted

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;};

http://img2.58codes.com/2024/20124767HhYweh2cUt.jpg

http://img2.58codes.com/2024/20124767Pl6hgYA20G.jpg
里用 lr 指标指定阵列的两端并找到中间的值 mid,如果 mid 的值大于 r 的值,代表最小值在 mid 的右边,将 l 移动到 mid 右边一格再次找 lrmid,持续找到最小值。

Time complexity: O(logn)


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章