From abd2eff5a178359df24539bf8b0d5c7cff662633 Mon Sep 17 00:00:00 2001 From: Spxg Date: Fri, 7 Jun 2024 17:51:40 +0800 Subject: [PATCH] Add problem 0670: Maximum Swap --- src/lib.rs | 1 + src/problem_0670_maximum_swap/iterative.rs | 43 ++++++++++++++++++++++ src/problem_0670_maximum_swap/mod.rs | 35 ++++++++++++++++++ 3 files changed, 79 insertions(+) create mode 100644 src/problem_0670_maximum_swap/iterative.rs create mode 100644 src/problem_0670_maximum_swap/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 3b86510..0186be4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -375,6 +375,7 @@ pub mod problem_0650_2_keys_keyboard; pub mod problem_0653_two_sum_iv_input_is_a_bst; pub mod problem_0654_maximum_binary_tree; pub mod problem_0665_non_decreasing_array; +pub mod problem_0670_maximum_swap; pub mod problem_0673_number_of_longest_increasing_subsequence; pub mod problem_0674_longest_continuous_increasing_subsequence; pub mod problem_0677_map_sum_pairs; diff --git a/src/problem_0670_maximum_swap/iterative.rs b/src/problem_0670_maximum_swap/iterative.rs new file mode 100644 index 0000000..45c3e84 --- /dev/null +++ b/src/problem_0670_maximum_swap/iterative.rs @@ -0,0 +1,43 @@ +pub struct Solution; + +use std::collections::HashMap; + +impl Solution { + pub fn maximum_swap(num: i32) -> i32 { + let mut nums = Vec::new(); + let mut map = HashMap::new(); + let mut num = num; + while num != 0 { + let digit = num % 10; + map.entry(digit).or_insert_with(|| nums.len()); + nums.push(digit); + num /= 10; + } + + let mut nums_sorted = nums.clone(); + nums_sorted.sort_unstable(); + + for idx in (0..nums.len()).rev() { + if nums[idx] < nums_sorted[idx] { + nums.swap(idx, map[&nums_sorted[idx]]); + break; + } + } + + nums.into_iter().rev().fold(0, |acc, x| acc * 10 + x) + } +} + +impl super::Solution for Solution { + fn maximum_swap(num: i32) -> i32 { + Self::maximum_swap(num) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_0670_maximum_swap/mod.rs b/src/problem_0670_maximum_swap/mod.rs new file mode 100644 index 0000000..980d132 --- /dev/null +++ b/src/problem_0670_maximum_swap/mod.rs @@ -0,0 +1,35 @@ +pub mod iterative; + +pub trait Solution { + fn maximum_swap(num: i32) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + (0, 0), + (1, 1), + (2, 2), + (3, 3), + (4, 4), + (5, 5), + (6, 6), + (7, 7), + (8, 8), + (9, 9), + (10, 10), + (11, 11), + (12, 21), + (13, 31), + (2736, 7236), + (9973, 9973), + ]; + + for (num, expected) in test_cases { + assert_eq!(S::maximum_swap(num), expected); + } + } +}