593. 有效的正方形

99 阅读1分钟

image.png

image.png

class Solution {
    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
        Set<Integer> set = new HashSet<>();
        // 如果顶点相同
        if (p1[0] == p2[0] && p1[1] == p2[1] ||
            p1[0] == p3[0] && p1[1] == p3[1] ||
            p1[0] == p4[0] && p1[1] == p4[1] ||
            p2[0] == p3[0] && p2[1] == p3[1] ||
            p2[0] == p4[0] && p2[1] == p4[1] ||
            p3[0] == p4[0] && p3[1] == p4[1]) {
            return false;
        }
        // 计算六个连线的长度
        int l1 = (int) Math.pow((p1[0] - p2[0]), 2) + (int) Math.pow((p1[1] - p2[1]), 2);
        int l2 = (int) Math.pow((p1[0] - p3[0]), 2) + (int) Math.pow((p1[1] - p3[1]), 2);
        int l3 = (int) Math.pow((p1[0] - p4[0]), 2) + (int) Math.pow((p1[1] - p4[1]), 2);
        int l4 = (int) Math.pow((p2[0] - p3[0]), 2) + (int) Math.pow((p2[1] - p3[1]), 2);
        int l5 = (int) Math.pow((p2[0] - p4[0]), 2) + (int) Math.pow((p2[1] - p4[1]), 2);
        int l6 = (int) Math.pow((p3[0] - p4[0]), 2) + (int) Math.pow((p3[1] - p4[1]), 2);
        set.add(l1);
        set.add(l2);
        set.add(l3);
        set.add(l4);
        set.add(l5);
        set.add(l6);
        return set.size() == 2;
    }
}