classSolution { publicdoubleminAreaFreeRect(int[][] points) { intN= points.length; Point[] A = newPoint[N]; for (inti=0; i < N; ++i) A[i] = newPoint(points[i][0], points[i][1]);
Map<Integer, Map<Point, List<Point>>> seen = newHashMap(); for (inti=0; i < N; ++i) for (intj= i+1; j < N; ++j) { // center is twice actual to keep integer precision Pointcenter=newPoint(A[i].x + A[j].x, A[i].y + A[j].y);
doubleans= Double.MAX_VALUE; for (Map<Point, List<Point>> info: seen.values()) { for (Point center: info.keySet()) { // center is twice actual List<Point> candidates = info.get(center); intclen= candidates.size(); for (inti=0; i < clen; ++i) for (intj= i+1; j < clen; ++j) { PointP= candidates.get(i); PointQ= candidates.get(j); PointQ2=newPoint(center); Q2.translate(-Q.x, -Q.y); doublearea= P.distance(Q) * P.distance(Q2); if (area < ans) ans = area; } } }
return ans < Double.MAX_VALUE ? ans : 0; } }
[DYbWiAKp-Python]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution(object): defminAreaFreeRect(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 radius = abs(center - P) seen[center, radius].append(P)
ans = float("inf") for (center, radius), candidates in seen.iteritems(): for P, Q in itertools.combinations(candidates, 2): ans = min(ans, abs(P - Q) * abs(P - (2*center - Q)))
return ans if ans < float("inf") else0
复杂度分析
时间复杂度:O(N^2 \log N),其中 N 是点集 points 的大小。可以证明,被分到同一类的点对数量的上界为 \log N - 点击链接查看更多 。