Java - simple and easy to undertand


  • 0
    Z
    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
            HashMap<Integer,Integer> hp = new HashMap<Integer,Integer>();
            
            //side could be side or diagonal
            dist(p1,p2,hp);
            dist(p2,p3,hp);
            dist(p3,p4,hp);
            dist(p4,p1,hp);
            dist(p1,p3,hp);
            dist(p4,p2,hp);
            // there can be just 2 lengths, 4equal sides and 2 equal diagonals
            if(hp.size()!=2) return false;
            //the distribution has to be 4 and 2  
            for(Map.Entry entry : hp.entrySet()){
                int val= (int) entry.getValue();
                if(val==2 || val==4)
                return true;
                else
                return false;
            }
            return true;
        }
        
        public void dist(int[] a1, int[] a2,HashMap<Integer,Integer> hp){
            //calculate ditance between two points and add it to teh hashmap
            int dist = ( ((a1[0]-a2[0])*(a1[0]-a2[0])) + ((a1[1]-a2[1])*(a1[1]-a2[1])) );
            if(hp.containsKey(dist)){
                hp.put(dist,hp.get(dist)+1);
            }else{
                hp.put(dist,1);
            }
        }
    

Log in to reply
 

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