|
|
@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
use std::cmp::Ordering;
|
|
|
|
|
|
|
|
|
|
|
|
fn findMin(nums: Vec<i32>) -> i32 {
|
|
|
|
fn findMin(nums: Vec<i32>) -> i32 {
|
|
|
|
let mut res = nums[0] as i32;
|
|
|
|
let mut res = nums[0] as i32;
|
|
|
|
// The left and right pointers of the binary search
|
|
|
|
// The left and right pointers of the binary search
|
|
|
@ -5,24 +7,20 @@ fn findMin(nums: Vec<i32>) -> i32 {
|
|
|
|
|
|
|
|
|
|
|
|
// Binary search
|
|
|
|
// Binary search
|
|
|
|
while l <= r {
|
|
|
|
while l <= r {
|
|
|
|
// If the left value is smaller than the right value,
|
|
|
|
match nums[l].cmp(&nums[r]) {
|
|
|
|
// then the left value is the smallest
|
|
|
|
Ordering::Less | Ordering::Equal => { // The array is sorted
|
|
|
|
if nums[l] <= nums[r] {
|
|
|
|
res = res.min(nums[l]);
|
|
|
|
res = res.min(nums[l]);
|
|
|
|
break;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ordering::Greater => { // The array is rotated
|
|
|
|
// The middle value
|
|
|
|
let mid = l + (r - l) / 2; // The middle index
|
|
|
|
let mid = l + (r - l) / 2;
|
|
|
|
res = res.min(nums[mid]); // Update the minimum
|
|
|
|
// Update the smallest value
|
|
|
|
if nums[l] <= nums[mid] { // The left half is sorted
|
|
|
|
res = res.min(nums[mid]);
|
|
|
|
l = mid + 1;
|
|
|
|
|
|
|
|
} else { // The right half is sorted
|
|
|
|
// If the left value is smaller than the middle value,
|
|
|
|
r = mid - 1;
|
|
|
|
// then the smallest value is on the right side
|
|
|
|
}
|
|
|
|
if nums[l] <= nums[mid] {
|
|
|
|
}
|
|
|
|
l = mid + 1;
|
|
|
|
|
|
|
|
} else {
|
|
|
|
|
|
|
|
// Otherwise, the smallest value is on the left side
|
|
|
|
|
|
|
|
r = mid - 1;
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return res as i32;
|
|
|
|
return res as i32;
|
|
|
|