Java solution using HashMap


  • 0
    K
    public class Solution {
        public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
            HashMap<Integer, Integer> hm = new HashMap<>();
            updateHM(p1, p2, p3, p4, hm);
            updateHM(p2, p3, p4, p1, hm);
            updateHM(p3, p4, p1, p2, hm);
            updateHM(p4, p1, p2, p3, hm);
            if(hm.size() != 2) return false;
            boolean check_4 = false, check_8 = false;
            for(Integer key:hm.keySet()) {
                if(hm.get(key) == 4) check_4 = true;
                if(hm.get(key) == 8) check_8 = true; 
            }
            return check_4&&check_8;
        }
        
        private void updateHM(int[] p1, int[] p2, int[] p3, int[] p4, HashMap<Integer, Integer> hm) {
            hm.put(getDist(p1, p2), hm.getOrDefault(getDist(p1,p2), 0) + 1);
            hm.put(getDist(p1, p3), hm.getOrDefault(getDist(p1,p3), 0) + 1);
            hm.put(getDist(p1, p4), hm.getOrDefault(getDist(p1,p4), 0) + 1);
        }
        
        private int getDist(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.