diff --git a/README.md b/README.md index e20c603..f367dd1 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,10 @@ Rust标准库`std::collections`提供了4种通用容器类型,包含一下8 ### 数组/队列/集合/映射 +- [回旋镖的数量](src/array/number_of_boomerangs.rs) [数组, 哈希表, 数学] + + - LeetCode 447. 回旋镖的数量 + - [经营摩天轮的最大利润](src/array/maximum_profit_of_operating_a_centennial_wheel.rs) [数组, 模拟] - LeetCode 1599. 经营摩天轮的最大利润 diff --git a/images/array/number_of_boomerangs.jpeg b/images/array/number_of_boomerangs.jpeg new file mode 100644 index 0000000..be49f19 Binary files /dev/null and b/images/array/number_of_boomerangs.jpeg differ diff --git a/src/array/mod.rs b/src/array/mod.rs index 4d46d10..fab0633 100644 --- a/src/array/mod.rs +++ b/src/array/mod.rs @@ -53,3 +53,4 @@ pub mod house_robber; pub mod stamping_the_grid; pub mod min_cost_climbing_stairs; pub mod maximum_profit_of_operating_a_centennial_wheel; +pub mod number_of_boomerangs; diff --git a/src/array/number_of_boomerangs.rs b/src/array/number_of_boomerangs.rs new file mode 100644 index 0000000..5c13e1c --- /dev/null +++ b/src/array/number_of_boomerangs.rs @@ -0,0 +1,28 @@ +// 回旋镖的数量 +// https://leetcode.cn/problems/number-of-boomerangs +// INLINE ../../images/array/number_of_boomerangs.jpeg + +pub struct Solution; + +impl Solution { + fn distance(p1: &Vec, p2: &Vec) -> i32 { + (p1[0] - p2[0]).pow(2) + (p1[1] - p2[1]).pow(2) + } + pub fn number_of_boomerangs(points: Vec>) -> i32 { + let mut res = 0; + for i in 0..points.len() { + let mut map = std::collections::HashMap::new(); + for j in 0..points.len() { + if i != j { + let distance = Solution::distance(&points[i], &points[j]); + let count = map.entry(distance).or_insert(0); + *count += 1; + } + } + for (_, v) in map { + res += v * (v - 1); + } + } + res + } +} diff --git a/tests/array/mod.rs b/tests/array/mod.rs index 7002d95..f92555a 100644 --- a/tests/array/mod.rs +++ b/tests/array/mod.rs @@ -53,3 +53,4 @@ pub mod house_robber_test; pub mod stamping_the_grid_test; pub mod min_cost_climbing_stairs_test; pub mod maximum_profit_of_operating_a_centennial_wheel_test; +pub mod number_of_boomerangs_test; diff --git a/tests/array/number_of_boomerangs_test.rs b/tests/array/number_of_boomerangs_test.rs new file mode 100644 index 0000000..982c6ce --- /dev/null +++ b/tests/array/number_of_boomerangs_test.rs @@ -0,0 +1,23 @@ +use rust_practice::array::number_of_boomerangs::Solution; + +#[test] +fn number_of_boomerangs() { + // 示例 1: + // 输入:points = [[0,0],[1,0],[2,0]] + // 输出:2 + // 解释:两个回旋镖为 [[1,0],[0,0],[2,0]] 和 [[1,0],[2,0],[0,0]] + let points = vec![vec![0, 0], vec![1, 0], vec![2, 0]]; + assert_eq!(Solution::number_of_boomerangs(points), 2); + + // 示例 2: + // 输入:points = [[1,1],[2,2],[3,3]] + // 输出:2 + let points = vec![vec![1, 1], vec![2, 2], vec![3, 3]]; + assert_eq!(Solution::number_of_boomerangs(points), 2); + + // 示例 3: + // 输入:points = [[1,1]] + // 输出:0 + let points = vec![vec![1, 1]]; + assert_eq!(Solution::number_of_boomerangs(points), 0); +}