feat: 2001_number_of_pairs_of_interchangeable_rectangles

This commit is contained in:
SquidSpirit 2025-09-20 04:57:01 +08:00
parent fc918a0a7d
commit 13d530c652
3 changed files with 41 additions and 0 deletions

View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "number_of_pairs_of_interchangeable_rectangles"
version = "0.1.0"

View File

@ -0,0 +1,6 @@
[package]
name = "number_of_pairs_of_interchangeable_rectangles"
version = "0.1.0"
edition = "2024"
[dependencies]

View File

@ -0,0 +1,28 @@
pub struct Solution;
impl Solution {
pub fn interchangeable_rectangles(rectangles: Vec<Vec<i32>>) -> i64 {
let mut groups = std::collections::HashMap::new();
for rect in rectangles {
let gcd = Solution::gcd(rect[0], rect[1]);
let ratio = (rect[0] / gcd, rect[1] / gcd);
groups
.entry(ratio)
.and_modify(|count| *count += 1)
.or_insert(1);
}
groups.values().map(|&n| n * (n - 1) / 2).sum()
}
fn gcd(a: i32, b: i32) -> i32 {
if a == 0 {
b
} else if a <= b {
Solution::gcd(b % a, a)
} else {
Solution::gcd(b, a)
}
}
}