From f54c84ac6ab6c02edf8a7c9a0ba5a5bdb6b8aee7 Mon Sep 17 00:00:00 2001 From: Luca Lombardo Date: Sat, 30 Sep 2023 19:28:12 +0200 Subject: [PATCH] modified the binary searches, now implemented with pattern matching --- .../src/main.rs | 22 ++++++------ .../src/main.rs | 34 +++++++++---------- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/2023_09_25/First_and_Last_Position_of_Element_in_Sorted_Array/src/main.rs b/2023_09_25/First_and_Last_Position_of_Element_in_Sorted_Array/src/main.rs index 92f37eb..5c7bcc0 100644 --- a/2023_09_25/First_and_Last_Position_of_Element_in_Sorted_Array/src/main.rs +++ b/2023_09_25/First_and_Last_Position_of_Element_in_Sorted_Array/src/main.rs @@ -1,3 +1,5 @@ +use std::cmp::Ordering; + struct Solution {} impl Solution { @@ -11,16 +13,16 @@ impl Solution { while l <= r { let m = l + (r - l) / 2; // m = middle for the binary search - if target > nums[m as usize] { - l = m + 1; - } else if target < nums[m as usize] { - r = m - 1; - } else { - i = m; - if left_bias { - r = m - 1; - } else { - l = m + 1; + match target.cmp(&nums[m as usize]) { + Ordering::Less => r = m - 1, + Ordering::Greater => l = m + 1, + Ordering::Equal => { + i = m; + if left_bias { + r = m - 1; + } else { + l = m + 1; + } } } } diff --git a/2023_09_25/find-minimum-in-rotated-sorted-array/src/main.rs b/2023_09_25/find-minimum-in-rotated-sorted-array/src/main.rs index 51ee204..d28e28d 100644 --- a/2023_09_25/find-minimum-in-rotated-sorted-array/src/main.rs +++ b/2023_09_25/find-minimum-in-rotated-sorted-array/src/main.rs @@ -1,3 +1,5 @@ +use std::cmp::Ordering; + fn findMin(nums: Vec) -> i32 { let mut res = nums[0] as i32; // The left and right pointers of the binary search @@ -5,24 +7,20 @@ fn findMin(nums: Vec) -> i32 { // Binary search while l <= r { - // If the left value is smaller than the right value, - // then the left value is the smallest - if nums[l] <= nums[r] { - res = res.min(nums[l]); - break; - } - // The middle value - let mid = l + (r - l) / 2; - // Update the smallest value - res = res.min(nums[mid]); - - // 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; - } else { - // Otherwise, the smallest value is on the left side - r = mid - 1; + match nums[l].cmp(&nums[r]) { + Ordering::Less | Ordering::Equal => { // The array is sorted + res = res.min(nums[l]); + break; + } + Ordering::Greater => { // The array is rotated + let mid = l + (r - l) / 2; // The middle index + res = res.min(nums[mid]); // Update the minimum + if nums[l] <= nums[mid] { // The left half is sorted + l = mid + 1; + } else { // The right half is sorted + r = mid - 1; + } + } } } return res as i32;