[JAVA - 22ms] using HashSet and comparing sides and the diagonal


  • 0
    S
    public class Solution {
        public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
            Set<Double> dist = new HashSet<Double>();
            dist.add(getDistance(p1, p2));
            dist.add(getDistance(p2, p3));
            dist.add(getDistance(p3, p4));
            dist.add(getDistance(p4, p1));
            dist.add(getDistance(p1, p3));
            dist.add(getDistance(p2, p4));
            
            if(dist.size() != 2 ) return false;
            
            double min = Double.MAX_VALUE;
            double max = Double.MIN_VALUE;
            
            for(double d : dist){
                min = Math.min(min, d);
                max = Math.max(max, d);
            }
            return (Math.abs(Math.sqrt(2*Math.pow(min,2) ) - max) <= 0.0000001) ? true : false;
        }
        
        private double getDistance(int[] p1, int[] p2){
            return Math.sqrt(Math.pow((p1[0] - p2[0]),2)+Math.pow((p1[1] - p2[1]),2));
        }
    }
    

Log in to reply
 

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