leetcode 939 Minimum Area Rectangle
1.题目描述
给定在 xy 平面上的一组点,确定由这些点组成的矩形的最小面积,其中矩形的边平行于 x 轴和 y 轴。
如果没有任何矩形,就返回 0。
示例 1:
输入:[[1,1],[1,3],[3,1],[3,3],[2,2]]
输出:4
示例 2:
输入:[[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]
输出:2
提示:
1 <= points.length <= 500
0 <= points[i][0] <= 40000
0 <= points[i][1] <= 40000
所有的点都是不同的。
2.解题思路
参考lee215代码
暴力搜索。
按顺序一个一个在seen
集合中加入点,并检测是否有满足条件的矩形出现,若有新的矩形的话不断更新最小矩形res
。
3.Python代码
class Solution:
def minAreaRect(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
seen = set()
res = float('inf')
for x1, y1 in points:
for x2, y2 in seen:
if (x1, y2) in seen and (x2, y1) in seen:
area = abs(x1 - x2) * abs(y1 - y2)
if area and area < res:
res = area
seen.add((x1, y1))
return res if res < float('inf') else 0