1. 程式人生 > >leetcode 939 Minimum Area Rectangle

leetcode 939 Minimum Area Rectangle

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