leetcode 593. Valid Square | 593. 有效的正方形(Java)

题目

https://leetcode.com/problems/valid-square/
leetcode 593. Valid Square | 593. 有效的正方形(Java)

题解

因为顺序未知,所以可能有四种组合情况。(check时,以四个点顺时针排列为待判断的正方形)

class Solution {
    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
        return check(p1, p2, p3, p4) || check(p1, p2, p4, p3) ||
                check(p1, p3, p2, p4) || check(p1, p3, p4, p2);
    }

    public boolean check(int[] A, int[] B, int[] C, int[] D) {
        if (distance(A, B) != distance(C, D) || distance(A, B) != distance(B, C) ||
                distance(A, D) != distance(B, C)) return false;
        // AB⊥AD
        double kAB = slope(A, B);
        double kAD = slope(A, D);
        if (kAB == Integer.MAX_VALUE) return kAD == 0;
        if (kAD == Integer.MAX_VALUE) return kAB == 0;
        return kAB * kAD - (-1) < 0.0001;
    }

    public int distance(int[] A, int[] B) {
        return (int) (Math.pow(B[1] - A[1], 2) + Math.pow(B[0] - A[0], 2));
    }

    public double slope(int[] A, int[] B) {
        if (B[0] - A[0] == 0) return Integer.MAX_VALUE; // inf
        else return (double) (B[1] - A[1]) / (B[0] - A[0]);
    }
}

leetcode 593. Valid Square | 593. 有效的正方形(Java)

上一篇:Server check fail, please check server 192.168.11.13 ,port 9848 is available , error ={}


下一篇:java开发自我介绍面试,Java架构师面试资料