diff --git a/src/leetcode/1534.count-good-triplets/Cargo.toml b/src/leetcode/1534.count-good-triplets/Cargo.toml new file mode 100644 index 00000000..e3839d29 --- /dev/null +++ b/src/leetcode/1534.count-good-triplets/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "lc-1534-count-good-triplets" +version = "0.1.0" +edition = "2021" +publish = false + +[dependencies] diff --git a/src/leetcode/1534.count-good-triplets/index.md b/src/leetcode/1534.count-good-triplets/index.md new file mode 100644 index 00000000..77a618ba --- /dev/null +++ b/src/leetcode/1534.count-good-triplets/index.md @@ -0,0 +1,4 @@ + +# + +[问题描述](../problems/) diff --git a/src/leetcode/1534.count-good-triplets/src/main.rs b/src/leetcode/1534.count-good-triplets/src/main.rs new file mode 100644 index 00000000..6f98a4bf --- /dev/null +++ b/src/leetcode/1534.count-good-triplets/src/main.rs @@ -0,0 +1,76 @@ +// Copyright (c) 2024 Xu Shaohua . All rights reserved. +// Use of this source is governed by General Public License that can be found +// in the LICENSE file. + +// Bruteforce +pub fn count_good_triplets1(arr: Vec, a: i32, b: i32, c: i32) -> i32 { + let len: usize = arr.len(); + let mut count: i32 = 0; + + // 三层嵌套循环 + for i in 0..(len - 2) { + for j in (i + 1)..(len - 1) { + for k in (j + 1)..len { + if (arr[i] - arr[j]).abs() <= a + && (arr[j] - arr[k]).abs() <= b + && (arr[i] - arr[k]).abs() <= c + { + count += 1; + } + } + } + } + count +} + +// 优化循环 +pub fn count_good_triplets2(arr: Vec, a: i32, b: i32, c: i32) -> i32 { + let len: usize = arr.len(); + let mut count: i32 = 0; + + // 三层嵌套循环 + for i in 0..(len - 2) { + for j in (i + 1)..(len - 1) { + if (arr[i] - arr[j]).abs() > a { + continue; + } + + for k in (j + 1)..len { + if (arr[j] - arr[k]).abs() <= b && (arr[i] - arr[k]).abs() <= c { + count += 1; + } + } + } + } + count +} + +pub type SolutionFn = fn(Vec, i32, i32, i32) -> i32; + +fn check_solution(func: SolutionFn) { + let arr = vec![3, 0, 1, 1, 9, 7]; + assert_eq!(func(arr, 7, 2, 3), 4); + + let arr = vec![1, 1, 2, 2, 3]; + assert_eq!(func(arr, 0, 0, 1), 0); +} + +fn main() { + check_solution(count_good_triplets1); + check_solution(count_good_triplets2); +} + +#[cfg(test)] +mod tests { + use super::{check_solution, count_good_triplets1, count_good_triplets2}; + + #[test] + fn test_count_good_triplets1() { + check_solution(count_good_triplets1); + } + + #[test] + fn test_count_good_triplets2() { + check_solution(count_good_triplets2); + } +}