mirror of
https://github.com/lukefleed/competitive-programming.git
synced 2026-10-06 14:14:52 +00:00
modified the binary searches, now implemented with pattern matching
This commit is contained in:
@@ -1,3 +1,5 @@
|
|||||||
|
use std::cmp::Ordering;
|
||||||
|
|
||||||
struct Solution {}
|
struct Solution {}
|
||||||
|
|
||||||
impl Solution {
|
impl Solution {
|
||||||
@@ -11,11 +13,10 @@ impl Solution {
|
|||||||
|
|
||||||
while l <= r {
|
while l <= r {
|
||||||
let m = l + (r - l) / 2; // m = middle for the binary search
|
let m = l + (r - l) / 2; // m = middle for the binary search
|
||||||
if target > nums[m as usize] {
|
match target.cmp(&nums[m as usize]) {
|
||||||
l = m + 1;
|
Ordering::Less => r = m - 1,
|
||||||
} else if target < nums[m as usize] {
|
Ordering::Greater => l = m + 1,
|
||||||
r = m - 1;
|
Ordering::Equal => {
|
||||||
} else {
|
|
||||||
i = m;
|
i = m;
|
||||||
if left_bias {
|
if left_bias {
|
||||||
r = m - 1;
|
r = m - 1;
|
||||||
@@ -24,6 +25,7 @@ impl Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
return i;
|
return i;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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,26 +7,22 @@ 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;
|
||||||
}
|
}
|
||||||
// The middle value
|
Ordering::Greater => { // The array is rotated
|
||||||
let mid = l + (r - l) / 2;
|
let mid = l + (r - l) / 2; // The middle index
|
||||||
// Update the smallest value
|
res = res.min(nums[mid]); // Update the minimum
|
||||||
res = res.min(nums[mid]);
|
if nums[l] <= nums[mid] { // The left half is sorted
|
||||||
|
|
||||||
// If the left value is smaller than the middle value,
|
|
||||||
// then the smallest value is on the right side
|
|
||||||
if nums[l] <= nums[mid] {
|
|
||||||
l = mid + 1;
|
l = mid + 1;
|
||||||
} else {
|
} else { // The right half is sorted
|
||||||
// Otherwise, the smallest value is on the left side
|
|
||||||
r = mid - 1;
|
r = mid - 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
return res as i32;
|
return res as i32;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user