LeetCode 题解工作台
可以形成最大正方形的矩形数目
给你一个数组 rectangles ,其中 rectangles[i] = [l i , w i ] 表示第 i 个矩形的长度为 l i 、宽度为 w i 。 如果存在 k 同时满足 k i 和 k i ,就可以将第 i 个矩形切成边长为 k 的正方形。例如,矩形 [4,6] 可以切成边长最大为 4…
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
我们定义一个变量 来记录当前最大边长的正方形的个数,定义另一个变量 来记录当前最大的边长。 遍历数组 ,对于每个矩形 $[l, w]$,我们取 $x = \min(l, w)$,如果 $mx < x$,说明我们找到了一个更大的边长,此时我们将 更新为 ,并将 更新为 ;如果 $mx = x$,说明我们找到了一个和当前最大边长相同的边长,此时我们将 增加 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
给你一个数组 rectangles ,其中 rectangles[i] = [li, wi] 表示第 i 个矩形的长度为 li 、宽度为 wi 。
如果存在 k 同时满足 k <= li 和 k <= wi ,就可以将第 i 个矩形切成边长为 k 的正方形。例如,矩形 [4,6] 可以切成边长最大为 4 的正方形。
设 maxLen 为可以从矩形数组 rectangles 切分得到的 最大正方形 的边长。
请你统计有多少个矩形能够切出边长为 maxLen 的正方形,并返回矩形 数目 。
示例 1:
输入:rectangles = [[5,8],[3,9],[5,12],[16,5]] 输出:3 解释:能从每个矩形中切出的最大正方形边长分别是 [5,3,5,5] 。 最大正方形的边长为 5 ,可以由 3 个矩形切分得到。
示例 2:
输入:rectangles = [[2,3],[3,7],[4,3],[3,7]] 输出:3
提示:
1 <= rectangles.length <= 1000rectangles[i].length == 21 <= li, wi <= 109li != wi
解题思路
方法一:一次遍历
我们定义一个变量 来记录当前最大边长的正方形的个数,定义另一个变量 来记录当前最大的边长。
遍历数组 ,对于每个矩形 ,我们取 ,如果 ,说明我们找到了一个更大的边长,此时我们将 更新为 ,并将 更新为 ;如果 ,说明我们找到了一个和当前最大边长相同的边长,此时我们将 增加 。
最后返回 即可。
时间复杂度 ,其中 为数组 的长度。空间复杂度 。
class Solution:
def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
ans = mx = 0
for l, w in rectangles:
x = min(l, w)
if mx < x:
ans = 1
mx = x
elif mx == x:
ans += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since each rectangle is processed once for max side computation and once for counting. Space complexity is O(1) if counting is done in-place, or O(n) if storing all max sides separately. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Checks if candidate immediately identifies min(length, width) as the key to largest square computation.
- question_mark
Observes whether candidate can efficiently track the largest square while iterating through rectangles.
- question_mark
Tests whether candidate handles multiple rectangles producing the same largest square correctly.
常见陷阱
外企场景- error
Forgetting to take min(length, width) and incorrectly using max or sum.
- error
Not correctly counting all rectangles that match the largest square size.
- error
Using nested loops unnecessarily instead of a single pass for max and count.
进阶变体
外企场景- arrow_right_alt
Return the indices of rectangles that can form the largest square instead of the count.
- arrow_right_alt
Allow rectangles to be rotated and compute largest square accordingly.
- arrow_right_alt
Find the second largest square and count rectangles that can form it.