You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle.
Two rectangles i and j (i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if widthi/heighti == widthj/heightj (using decimal division, not integer division).
Return the number of pairs of interchangeable rectangles inrectangles.
Rectangles are interchangeable if their width-to-height ratios are equal. By reducing each ratio to its simplest form (using GCD), we can count how many rectangles share the same ratio. For each group of rectangles with the same ratio, the number of interchangeable pairs is the combination C(n, 2) = n*(n-1)/2.
classSolution {
public:longlong interchangeableRectangles(vector<vector<int>>& rects) {
unordered_map<string, longlong> cnt;
for (auto& r : rects) {
int g = gcd(r[0], r[1]);
string key = to_string(r[0]/g) +"/"+ to_string(r[1]/g);
cnt[key]++;
}
longlong ans =0;
for (auto& [k, v] : cnt) ans += v * (v -1) /2;
return ans;
}
intgcd(int a, int b) { return b ? gcd(b, a % b) : a; }
};
classSolution {
publiclonginterchangeableRectangles(int[][] rects) {
Map<String, Long> cnt =new HashMap<>();
for (int[] r : rects) {
int g = gcd(r[0], r[1]);
String key = (r[0]/g) +"/"+ (r[1]/g);
cnt.put(key, cnt.getOrDefault(key, 0L) + 1);
}
long ans = 0;
for (long v : cnt.values()) ans += v * (v - 1) / 2;
return ans;
}
privateintgcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funinterchangeableRectangles(rects: Array<IntArray>): Long {
val cnt = mutableMapOf<String, Long>()
for (r in rects) {
val g = gcd(r[0], r[1])
val key = "${r[0]/g}/${r[1]/g}" cnt[key] = cnt.getOrDefault(key, 0L) + 1 }
var ans = 0Lfor (v in cnt.values) ans += v * (v - 1) / 2return ans
}
privatefungcd(a: Int, b: Int): Int = if (b ==0) a else gcd(b, a % b)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from collections import defaultdict
defgcd(a: int, b: int) -> int:
while b:
a, b = b, a % b
return a
classSolution:
definterchangeableRectangles(self, rects: list[list[int]]) -> int:
cnt: dict[tuple[int, int], int] = defaultdict(int)
for w, h in rects:
g = gcd(w, h)
cnt[(w//g, h//g)] +=1 ans =0for v in cnt.values():
ans += v * (v -1) //2return ans
use std::collections::HashMap;
impl Solution {
pubfninterchangeable_rectangles(rects: Vec<Vec<i32>>) -> i64 {
fngcd(mut a: i32, mut b: i32) -> i32 {
while b !=0 {
let t = b;
b = a % b;
a = t;
}
a
}
letmut cnt = HashMap::new();
for r in rects.iter() {
let g = gcd(r[0], r[1]);
let key = (r[0]/g, r[1]/g);
*cnt.entry(key).or_insert(0) +=1;
}
letmut ans =0i64;
for&v in cnt.values() {
ans += v * (v -1) /2;
}
ans
}
}