題目
解題思路
- 找出所有的矩形
- 逐一計算面積,找出面積最小的矩形
對於步驟1,判斷是否爲矩形的條件是:其對角線相交的中心點到四個角的距離相等。如下圖所示:
這裏有個小技巧,爲了對 list 中的點進行向量計算,我們使用 complex() 函數將這些點變爲複數形式。complex用法示例如下:
>>> complex(1, 2)
>>> (1 + 2j)
忘了向量運算的,可以稍微複習一下:
向量加法:A(x1, y1) + B (x2, y2) = (x1 + x2, y1 + y2)
向量減法:A(x1, y1) - B (x2, y2) = (x1 - x2, y1 - y2)
參考代碼(beats 95%):
'''
@auther: Jedi.L
@Date: Tue, Apr 30, 2019 3:40
@Email: [email protected]
@Blog: www.tundrazone.com
'''
import itertools
import collections
class Solution(object):
def minAreaFreeRect(self, points):
points = [complex(*z) for z in points]
seen = collections.defaultdict(list)
for P, Q in itertools.combinations(points, 2):
center = (P + Q) / 2 # get the center point
radius = abs(center - P) # caculate the distance
# Only record P here, because Q = 2 * center - P
seen[center, radius].append(P)
res = float("inf")
for (center, radius), candidates in seen.items():
for P, Q in itertools.combinations(candidates, 2):
# caculate area
res = min(res, abs(P - Q) * abs(P - (2 * center - Q)))
return res if res < float("inf") else 0