Java Solution,calculate distance by storing the points in a List


  • 0
    L
        public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
            List<int[]> points=new ArrayList<>();
            points.add(p1);
            points.add(p2);
            points.add(p3);
            points.add(p4);
            Map<Integer,Integer> distances=new HashMap<>();
            for(int i=0;i<points.size()-1;i++){
                for(int j=i+1;j<=points.size()-1;j++){
                    int dis=(points.get(i)[0]-points.get(j)[0])*(points.get(i)[0]-points.get(j)[0])+(points.get(i)[1]-points.get(j)[1])*(points.get(i)[1]-points.get(j)[1]);
                    distances.put(dis,distances.getOrDefault(dis,0)+1);
                }
            }
            if(distances.size()!=2)
                return false;
            int minDis=Integer.MAX_VALUE;
            int maxDis=Integer.MIN_VALUE;
            for(Integer key:distances.keySet()){
                if(key.intValue()>maxDis)
                    maxDis=key.intValue();
                if(key.intValue()<minDis)
                    minDis=key.intValue();
    
            }
            if(distances.get(minDis).intValue()==4&&distances.get(maxDis)==2&&minDis*2==maxDis){
                return true;
            }
            return false;
        }
    

Log in to reply
 

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