Skip to content

Commit

Permalink
add: 最大交换
Browse files Browse the repository at this point in the history
  • Loading branch information
yi-ge committed Jan 22, 2024
1 parent c722320 commit d197e4a
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -816,3 +816,7 @@ Rust标准库`std::collections`提供了4种通用容器类型,包含一下8
- [统计整数数目](src/math/count_of_integers.rs) [数学, 字符串, 动态规划]

- LeetCode 2719. 统计整数数目 <https://leetcode.cn/problems/count-of-integers>

- [最大交换](src/math/maximum_swap.rs) [贪心, 数学]

- LeetCode 670. 最大交换 <https://leetcode.cn/problems/maximum-swap>
Binary file added images/math/maximum_swap.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
31 changes: 31 additions & 0 deletions src/math/maximum_swap.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// 最大交换
// https://leetcode.cn/problems/maximum-swap
// INLINE ../../images/math/maximum_swap.jpeg

pub struct Solution;

impl Solution {
pub fn maximum_swap(num: i32) -> i32 {
let mut s: Vec<char> = num.to_string().chars().collect();
let n = s.len();
let mut max_idx = n - 1;
let mut idx1 = None;
let mut idx2 = None;

for i in (0..n).rev() {
if s[i] > s[max_idx] {
max_idx = i;
} else if s[i] < s[max_idx] {
idx1 = Some(i);
idx2 = Some(max_idx);
}
}

if let (Some(idx1), Some(idx2)) = (idx1, idx2) {
s.swap(idx1, idx2);
s.iter().collect::<String>().parse::<i32>().unwrap_or(num)
} else {
num
}
}
}
1 change: 1 addition & 0 deletions src/math/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ pub mod maximum_students_taking_exam;
pub mod day_of_the_week;
pub mod maximum_rows_covered_by_columns;
pub mod count_of_integers;
pub mod maximum_swap;
20 changes: 20 additions & 0 deletions tests/math/maximum_swap_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use rust_practice::math::maximum_swap::Solution;

#[test]
fn maximum_swap_test() {
// 示例 1 :
// 输入: 2736
// 输出: 7236
// 解释: 交换数字2和数字7。
let num = 2736;
let result = Solution::maximum_swap(num);
assert_eq!(result, 7236);

// 示例 2 :
// 输入: 9973
// 输出: 9973
// 解释: 不需要交换。
let num = 9973;
let result = Solution::maximum_swap(num);
assert_eq!(result, 9973);
}
1 change: 1 addition & 0 deletions tests/math/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ pub mod maximum_students_taking_exam_test;
pub mod day_of_the_week_test;
pub mod maximum_rows_covered_by_columns_test;
pub mod count_of_integers_test;
pub mod maximum_swap_test;

0 comments on commit d197e4a

Please sign in to comment.