153. 寻找旋转排序数组中的最小值
153. 寻找旋转排序数组中的最小值
题目
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 rotated4
times.[0,1,2,4,5,6,7]
if it was rotated7
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.
Example 2:
Input: nums = [4,5,6,7,0,1,2]
Output: 0
Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.
Example 3:
Input: nums = [11,13,15,17]
Output: 11
Explanation: The original array was [11,13,15,17] and it was rotated 4 times.
Constraints:
n == nums.length
1 <= n <= 5000
-5000 <= nums[i] <= 5000
- All the integers of
nums
are unique. nums
is sorted and rotated between1
andn
times.
题目大意
假设按照升序排序的数组在预先未知的某个点上进行了旋转。(例如,数组 [0,1,2,4,5,6,7]
可能变为 [4,5,6,7,0,1,2]
)。请找出其中最小的元素。
你可以假设数组中不存在重复元素。
解题思路
最直接的办法就是遍历一遍,找到最小值。但是还可以有更好的方法,可以用二分查找来降低算法的时间复杂度。
创建两个指针 left
、right
,分别指向数组首尾,然后计算出两个指针所指下标的中间值 mid
,将 mid
与两个指针做比较。
- 如果
nums[mid] > nums[right]
,则最小值不可能在mid
左侧,一定在mid
右侧,则将left
移动到mid + 1
位置,继续查找右侧区间。 - 如果
nums[mid] <= nums[right]
,则最小值一定在mid
左侧,或者mid
位置,将right
移动到mid
位置上,继续查找左侧区间。
复杂度分析
- 时间复杂度:
O(log n)
- 空间复杂度:
O(1)
代码
/**
* @param {number[]} nums
* @return {number}
*/
var findMin = function (nums) {
let left = 0,
right = nums.length - 1;
while (left < right) {
let mid = Math.floor((left + right) / 2);
if (nums[mid] > nums[right]) {
left = mid + 1;
} else {
right = mid;
}
}
return nums[left];
};
相关题目
题号 | 标题 | 题解 | 标签 | 难度 |
---|---|---|---|---|
33 | 搜索旋转排序数组 | [✓] | 数组 二分查找 | |
154 | 寻找旋转排序数组中的最小值 II | [✓] | 数组 二分查找 |