LeetCode 题解工作台
可互换矩形的组数
用一个下标从 0 开始的二维整数数组 rectangles 来表示 n 个矩形,其中 rectangles[i] = [width i , height i ] 表示第 i 个矩形的宽度和高度。 如果两个矩形 i 和 j ( i )的宽高比相同,则认为这两个矩形 可互换 。更规范的说法是,两个矩形满…
5
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
为了能够唯一表示矩形,我们需要将矩形的宽高比化简为最简分数。因此,我们可以求出每个矩形的宽高比的最大公约数,然后将宽高比化简为最简分数。接下来,我们使用哈希表统计每个最简分数的矩形数量,然后计算每个最简分数的矩形数量的组合数,即可得到答案。 时间复杂度 $O(n \times \log M)$,空间复杂度 。其中 和 分别是矩形的数量和矩形的最大边长。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
用一个下标从 0 开始的二维整数数组 rectangles 来表示 n 个矩形,其中 rectangles[i] = [widthi, heighti] 表示第 i 个矩形的宽度和高度。
如果两个矩形 i 和 j(i < j)的宽高比相同,则认为这两个矩形 可互换 。更规范的说法是,两个矩形满足 widthi/heighti == widthj/heightj(使用实数除法而非整数除法),则认为这两个矩形 可互换 。
计算并返回 rectangles 中有多少对 可互换 矩形。
示例 1:
输入:rectangles = [[4,8],[3,6],[10,20],[15,30]] 输出:6 解释:下面按下标(从 0 开始)列出可互换矩形的配对情况: - 矩形 0 和矩形 1 :4/8 == 3/6 - 矩形 0 和矩形 2 :4/8 == 10/20 - 矩形 0 和矩形 3 :4/8 == 15/30 - 矩形 1 和矩形 2 :3/6 == 10/20 - 矩形 1 和矩形 3 :3/6 == 15/30 - 矩形 2 和矩形 3 :10/20 == 15/30
示例 2:
输入:rectangles = [[4,5],[7,8]] 输出:0 解释:不存在成对的可互换矩形。
提示:
n == rectangles.length1 <= n <= 105rectangles[i].length == 21 <= widthi, heighti <= 105
解题思路
方法一:数学 + 哈希表
为了能够唯一表示矩形,我们需要将矩形的宽高比化简为最简分数。因此,我们可以求出每个矩形的宽高比的最大公约数,然后将宽高比化简为最简分数。接下来,我们使用哈希表统计每个最简分数的矩形数量,然后计算每个最简分数的矩形数量的组合数,即可得到答案。
时间复杂度 ,空间复杂度 。其中 和 分别是矩形的数量和矩形的最大边长。
class Solution:
def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:
ans = 0
cnt = Counter()
for w, h in rectangles:
g = gcd(w, h)
w, h = w // g, h // g
ans += cnt[(w, h)]
cnt[(w, h)] += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) due to a single pass through the rectangles and O(1) hash operations per rectangle. Space complexity is O(n) for storing ratio counts in the hash map. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for candidates to optimize from O(n^2) pair checking to hash-based counting.
- question_mark
Expect discussion on precision when dividing integers to form accurate ratios.
- question_mark
Check whether candidates consider edge cases with identical width or height values.
常见陷阱
外企场景- error
Using integer division instead of decimal division when calculating ratios, leading to incorrect pair counting.
- error
Nested loops for pair comparison, which causes timeouts on large inputs.
- error
Failing to correctly increment pair counts based on existing ratio counts in the hash map.
进阶变体
外企场景- arrow_right_alt
Count pairs of rectangles that are exact matches in width and height instead of ratios.
- arrow_right_alt
Return the list of all interchangeable rectangle index pairs rather than just the count.
- arrow_right_alt
Handle rectangles where dimensions are very large, requiring careful numeric precision for ratios.