Java (16 ms)


  • 0
    K

    class Solution {

    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {        
        int[][] points = new int[][] {
            p1, p2, p3, p4
        };
        
        long side = -1, diag = -1, dist;
        short sideCount = 0, diagCount = 0;
        
        for (int i = 0; i < 4; i++) {
            for (int j = i + 1; j < 4; j++) {
                dist = (long) (Math.pow(points[i][0] - points[j][0], 2) + Math.pow(points[i][1] - points[j][1], 2));
                
                if (side < 0) {
                    side = dist;
                } else if (diag < 0 && dist != side) {
                    if (dist > side) {
                        diag = dist;
                    } else {
                        diag = side;
                        diagCount = sideCount;
    
                        side = dist;
                        sideCount = 0;
                    }
                    
                    if (diag / 2 != side) {
                        return false;
                    }
                } 
                
                if (dist == side) {
                    sideCount++;
                } else if (dist == diag) {
                    diagCount++;
                } else {
                    return false;
                }
            }
        }
        return sideCount == 4 && diagCount == 2;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.