Minimum in Rotated Sorted Array
Medium binary-search · arrays
Description
Constraints
1 <= n <= 100000; values are distinct
Examples
Input: nums = [3,4,5,1,2]
Output: 1
Hints (1)
- Compare the middle value with the right end to decide which half holds the minimum.
Solutions
Binary search against the right end. · Time O(log n) · Space O(1)
func findMin(nums []int) int {
lo, hi := 0, len(nums)-1
for lo < hi {
mid := (lo + hi) / 2
if nums[mid] > nums[hi] {
lo = mid + 1
} else {
hi = mid
}
}
return nums[lo]
}
Binary search against the right end. · Time O(log n) · Space O(1)
function findMin(nums) {
let lo = 0, hi = nums.length - 1;
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
if (nums[mid] > nums[hi]) lo = mid + 1; else hi = mid;
}
return nums[lo];
}
Binary search against the right end. · Time O(log n) · Space O(1)
function findMin($nums) {
$lo = 0; $hi = count($nums) - 1;
while ($lo < $hi) {
$mid = intdiv($lo + $hi, 2);
if ($nums[$mid] > $nums[$hi]) { $lo = $mid + 1; } else { $hi = $mid; }
}
return $nums[$lo];
}
Binary search against the right end. · Time O(log n) · Space O(1)
def findMin(nums):
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] > nums[hi]:
lo = mid + 1
else:
hi = mid
return nums[lo]
Binary search against the right end. · Time O(log n) · Space O(1)
function findMin(nums: number[]): number {
let lo = 0, hi = nums.length - 1;
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
if (nums[mid] > nums[hi]) lo = mid + 1; else hi = mid;
}
return nums[lo];
}
Create a free account to submit solutions, track progress and save problems.
Create account