LeetCode 593. 有效的正方形

思路
判断正方形: 用一个数组用于保存四个点之间的距离,求出两两点之间的距离,若数组不存在所求的距离数值,则添加进数组,若数组超过三个数值,则返回FALSE,否则返回true(其实只要两个就行了,不用距离平方比为1/2,自己举例证明…)

public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {

        if (Arrays.equals(p1, p2) || Arrays.equals(p1, p3) || Arrays.equals(p1, p4) || Arrays.equals(p2, p3) ||
                Arrays.equals(p2, p4) || Arrays.equals(p3, p4)) {
            return false;
        }

        int x1 = p1[0];
        int x2 = p2[0];
        int x3 = p3[0];
        int x4 = p4[0];

        int y1 = p1[1];
        int y2 = p2[1];
        int y3 = p3[1];
        int y4 = p4[1];

        HashSet<Double> set = new HashSet<>();

        set.add(Math.sqrt(Math.abs(x1 - x2) * Math.abs(x1 - x2) + Math.abs(y1 - y2) * Math.abs(y1 - y2)));
        set.add(Math.sqrt(Math.abs(x1 - x3) * Math.abs(x1 - x3) + Math.abs(y1 - y3) * Math.abs(y1 - y3)));
        set.add(Math.sqrt(Math.abs(x1 - x4) * Math.abs(x1 - x4) + Math.abs(y1 - y4) * Math.abs(y1 - y4)));

        set.add(Math.sqrt(Math.abs(x2 - x3) * Math.abs(x2 - x3) + Math.abs(y2 - y3) * Math.abs(y2 - y3)));
        set.add(Math.sqrt(Math.abs(x2 - x4) * Math.abs(x2 - x4) + Math.abs(y2 - y4) * Math.abs(y2 - y4)));

        set.add(Math.sqrt(Math.abs(x3 - x4) * Math.abs(x3 - x4) + Math.abs(y3 - y4) * Math.abs(y3 - y4)));

        return set.size() < 3;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值