Valid Square

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

根据四个二维坐标,判断这四个点能否构成一个正方形。

思路1:

根据正方形的特点,任意两点之间的距离只有两种, 一是边,二是对角线;根据这个特性,计算任意两点之间距离。

public class Solution {
    
    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {  
        HashSet set = new HashSet();  
        int d1 = distance(p1, p2);  
        int d2 = distance(p1, p3);  
        int d3 = distance(p1, p4);  
        int d4 = distance(p2, p3);  
        int d5 = distance(p2, p4);  
        int d6 = distance(p3, p4);  
        if (d1 == 0 || d2 == 0 || d3 == 0 || d4 == 0 || d5 == 0 || d6 == 0)  
            return false;  
        set.add(d1);  
        set.add(d2);  
        set.add(d3);  
        set.add(d4);  
        set.add(d5);  
        set.add(d6);  
        if (set.size() == 2)  
            return true;  
        return false;  
    }  
  
    private int distance(int[] x, int[] y) {  
        return (int) (Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2));  
    } 
     
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值