Valid Square

Given the coordinates of four points in 2D space, return whether the four points could construct a square.

The coordinate (x,y) of a point is represented by an integer array with two integers.

Example:

Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: True

思路:就是每两个点的距离,要么是a要么是Sqrt(2)*a, 只能有两种值。set中不能有0,因为point有重合的点;

class Solution {
    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
        if(p1 == null || p2 == null || p3 == null || p4 == null
          || p1.length <= 1 || p2.length <= 1 || p3.length <= 1 || p4.length <= 1) {
            return false;
        }
        
        HashSet<Integer> set = new HashSet<Integer>();
        ArrayList<int[]> list = new ArrayList<>();
        list.add(p1); list.add(p2);list.add(p3);list.add(p4);
        
        for(int i = 0; i < list.size(); i++) {
            for(int j = i + 1; j < list.size(); j++) {
                int dis = getDistance(list.get(i), list.get(j));
                set.add(dis);
            }
        }
        return !set.contains(0) && set.size() == 2;
    }
    
    private int getDistance(int[] p1, int[] p2) {
        int x1 = p1[0]; 
        int y1 = p1[1];
        
        int x2 = p2[0]; 
        int y2 = p2[1];
        
        return (x2 - x1) * (x2 - x1) + (y2 - y1) *(y2 - y1);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值