Given a set of points in the xy-plane, determine the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the x and y axes.
If there isn't any rectangle, return 0.
Example 1:
Input: [[1,2],[2,1],[1,0],[0,1]] Output: 2.00000 Explanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.
Example 2:
Input: [[0,1],[2,1],[1,1],[1,0],[2,0]] Output: 1.00000 Explanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.
Example 3:
Input: [[0,3],[1,2],[3,1],[1,3],[2,1]] Output: 0 Explanation: There is no possible rectangle to form from these points.
Example 4:
Input: [[3,1],[1,1],[0,1],[2,1],[3,3],[3,2],[0,2],[2,3]] Output: 2.00000 Explanation: The minimum area rectangle occurs at [2,1],[2,3],[3,3],[3,1], with an area of 2.
Note:
1 <= points.length <= 50
0 <= points[i][0] <= 40000
0 <= points[i][1] <= 40000
- All points are distinct.
- Answers within
10^-5
of the actual value will be accepted as correct.
思路:暴力求解,遍历矩形3个点的位置,另外一个点可以通过已知的3个点求出来,注意:
(1)水平线,竖直线斜率的求解
(2)Python做些prune才能AC,可以Run Code看超时case的运行时间
import math
class Solution(object):
def minAreaFreeRect(self, points):
"""
:type points: List[List[int]]
:rtype: float
"""
s = set([tuple(t) for t in points])
res = float('inf')
n=len(points)
for i in range(n):
xi,yi = points[i]
for j in range(i+1, n):
# if j==i: continue
xj,yj = points[j]
if (xj-xi)**2+(yj-yi)**2>=res: continue
k_ij = (yj-yi)/(xj-xi+0.0) if xi!=xj else float('inf')
for k in range(n):
if k==i or k==j: continue
xk,yk = points[k]
k_jk = (yk-yj)/(xk-xj+0.0) if xk!=xj else float('inf')
if (k_ij,k_jk)==(float('inf'),0) or (k_ij,k_jk)==(0,float('inf')):
pass
else:
if abs(-1-k_ij*k_jk)>0.00001: continue
xl,yl=(xi+xk-xj),(yi+yk-yj)
if (xl,yl) in s:
a2 = (xj-xi)**2+(yj-yi)**2
b2 = (xk-xj)**2+(yk-yj)**2
res = min(res, a2*b2)
return math.sqrt(res) if res!=float('inf') else 0