打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
0593. Valid Square (M)
userphoto

2022.10.06 北京

关注

Valid Square (M)

题目

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

Note:

  1. All the input integers are in the range [-10000, 10000].
  2. A valid square has four equal sides with positive length and four equal angles (90-degree angles).
  3. Input points have no order.

题意

给定四个点的坐标,判断这四个点能否组成正方形。

思路

按照x坐标从小到大、y坐标从小到大的优先级进行排序,记此时四个点为a、b、c、d,如果能形成正方形,那么四条边分别是ab、ac、bd、cd。只要判断四条边是否相等,以及对角线是否相等即可(需要先排除所有点在一个位置这一特殊情况)。


代码实现

Java

class Solution {
    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
        int[][] points = { p1, p2, p3, p4 };
        Arrays.sort(points, (p, q) -> p[0] == q[0] ? p[1] - q[1] : p[0] - q[0]);
        return calc(points[0], points[1]) != 0
                && calc(points[0], points[1]) == calc(points[0], points[2])
                && calc(points[3], points[1]) == calc(points[3], points[2])
                && calc(points[0], points[1]) == calc(points[3], points[1])
                && calc(points[0], points[3]) == calc(points[1], points[2]);
    }

    private int calc(int[] p, int[] q) {
        int a = p[0] - q[0], b = p[1] - q[1];
        return a * a + b * b;
    }
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
剑指offer 51数组中重复的数字
PAT A1154 Vertex Coloring (25 分)
微软2013暑假实习生笔试题
1537. Get the Maximum Score
【python】点燃我,温暖你 ,快来Get同款~
集训队简单数学专题
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服