GuilinDev

Lc0963

05 August 2008

963. Minimum Area Rectangle II

给定 X-Y​​ 平面中的点数组,其中 points[i] = [xi, yi]。

返回由这些点形成的任何矩形的最小面积,其边不一定平行于 X 和 Y 轴。如果不存在这样的矩形,则返回 0。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
    public double minAreaFreeRect(int[][] points) {
        if (points.length < 4) {
            return 0;
        }

        Set<String> set = new HashSet<>();
        for (int i = 0; i < points.length; i++) {
            set.add(format().apply(points[i]));
        }

        double area = 0;
        for (int i = 0; i < points.length; i++) {
            for (int j = i + 1; j < points.length; j++) {
                int d2ij = distance2(points[i], points[j]);
                for (int k = j + 1; k < points.length; k++) {
                    int d2ik = distance2(points[i], points[k]);
                    int d2jk = distance2(points[j], points[k]);
                    if (d2ij + d2ik != d2jk) {
                        continue;
                    }

                    int x = points[j][0] + points[k][0] - points[i][0];
                    int y = points[j][1] + points[k][1] - points[i][1];
                    int[] pointXY = new int[]{x, y};
                    if (!set.contains(format().apply(pointXY))) {
                        continue;
                    }

                    double tmpArea = Math.sqrt(d2ij) * Math.sqrt(d2ik);
                    if (area == 0 || area > tmpArea) {
                        area = tmpArea;
                    }
                }
            }
        }

        return area;
    }

    private Function<int[], String> format() {
        return point -> String.format("%d_%d", point[0], point[1]);
    }

    private int distance2(int[] a, int[] b) {
        return (b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1]);
    }

}