diff --git a/.vscode/settings.json b/.vscode/settings.json index 31d5771..0ed956f 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -38,6 +38,7 @@ "cabac", "camelcase", "Ccodegen", + "choco", "coverallsapp", "Coverflow", "Cpanic", diff --git a/README.md b/README.md index 50cb2d0..e4ad94b 100644 --- a/README.md +++ b/README.md @@ -519,6 +519,10 @@ Rust标准库`std::collections`提供了4种通用容器类型,包含一下8 ### 排序 +- [购买两块巧克力](src/sort/buy_two_chocolates.rs) [数组, 排序] + + - LeetCode 2706. 购买两块巧克力 + - [下一个更大元素 IV](src/sort/next_greater_element_iv.rs) [栈, 数组, 二分查找, 排序, 单调栈, 堆(优先队列)] - LeetCode 2454. 下一个更大元素 IV diff --git a/images/sort/buy_two_chocolates.jpeg b/images/sort/buy_two_chocolates.jpeg new file mode 100644 index 0000000..e85e853 Binary files /dev/null and b/images/sort/buy_two_chocolates.jpeg differ diff --git a/src/sort/buy_two_chocolates.rs b/src/sort/buy_two_chocolates.rs new file mode 100644 index 0000000..40702ff --- /dev/null +++ b/src/sort/buy_two_chocolates.rs @@ -0,0 +1,25 @@ +// 购买两块巧克力 +// https://leetcode.cn/problems/buy-two-chocolates +// INLINE ../../images/sort/buy_two_chocolates.jpeg + +pub struct Solution; + +impl Solution { + pub fn buy_choco(prices: Vec, money: i32) -> i32 { + let mut fi = i32::MAX; + let mut se = i32::MAX; + for p in prices { + if p < fi { + se = fi; + fi = p; + } else if p < se { + se = p; + } + } + if money < fi + se { + money + } else { + money - fi - se + } + } +} diff --git a/src/sort/mod.rs b/src/sort/mod.rs index 65fff19..25dd835 100644 --- a/src/sort/mod.rs +++ b/src/sort/mod.rs @@ -21,3 +21,4 @@ pub mod compare_strings_by_frequency_of_the_smallest_character; pub mod greatest_sum_divisible_by_three; pub mod maximum_earnings_from_taxi; pub mod next_greater_element_iv; +pub mod buy_two_chocolates; diff --git a/tests/sort/buy_two_chocolates_test.rs b/tests/sort/buy_two_chocolates_test.rs new file mode 100644 index 0000000..5edce35 --- /dev/null +++ b/tests/sort/buy_two_chocolates_test.rs @@ -0,0 +1,20 @@ +use rust_practice::sort::buy_two_chocolates::Solution; + +#[test] +fn buy_choco() { + // 示例 1: + // 输入:prices = [1,2,2], money = 3 + // 输出:0 + // 解释:分别购买价格为 1 和 2 的巧克力。你剩下 3 - 3 = 0 块钱。所以我们返回 0 。 + let prices = vec![1, 2, 2]; + let money = 3; + assert_eq!(Solution::buy_choco(prices, money), 0); + + // 示例 2: + // 输入:prices = [3,2,3], money = 3 + // 输出:3 + // 解释:购买任意 2 块巧克力都会超过你拥有的钱数,所以我们返回 3 。 + let prices = vec![3, 2, 3]; + let money = 3; + assert_eq!(Solution::buy_choco(prices, money), 3); +} diff --git a/tests/sort/mod.rs b/tests/sort/mod.rs index 679c6be..c607e73 100644 --- a/tests/sort/mod.rs +++ b/tests/sort/mod.rs @@ -21,3 +21,4 @@ pub mod compare_strings_by_frequency_of_the_smallest_character_test; pub mod greatest_sum_divisible_by_three_test; pub mod maximum_earnings_from_taxi_test; pub mod next_greater_element_iv_test; +pub mod buy_two_chocolates_test;