Simple Java Solution Using Map


  • 0
    S
    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
            Map<Integer,Integer> map = new HashMap<>();
            int[] lengths = {length(p1, p2), length(p2, p3), length(p3, p4),
                length(p4, p1), length(p1, p3),length(p2, p4)};
            for(int l : lengths)
                map.put(l,map.getOrDefault(l,0) + 1);
            if(map.size() == 2 && map.values().contains(2) && map.values().contains(4)) // return true only if map contains 2 diagonals and 4 sides 
                   return true;
            return false;
        }
        
        private int length(int[] p1, int[] p2) {
            return ((p1[0]-p2[0]) * (p1[0]-p2[0])) + ((p1[1]-p2[1]) * (p1[1]-p2[1])) ;
        }
    

Log in to reply
 

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