[LeetCode] 593. Valid Square

Given the coordinates of four points in 2D space p1p2p3 and p4, return true if the four points construct a square.

The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order.

A valid square has four equal sides with positive length and four equal angles (90-degree angles).

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

  • p1.length == p2.length == p3.length == p4.length == 2
  • -104 <= xi, yi <= 104

有效的正方形。

给定2D空间中四个点的坐标 p1, p2, p3 和 p4,如果这四个点构成一个正方形,则返回 true 。

点的坐标 pi 表示为 [xi, yi] 。输入 不是 按任何顺序给出的。

一个 有效的正方形 有四条等边和四个等角(90度角)。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/valid-square
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这是一道数学题,我直接给出最优解。这个题虽然downvote比较多但是我觉得在几何题里面还是有练习价值的。如果要判断给定的四个点是否能组成正方形,因为四个点给的顺序是随机的,所以可以根据横坐标对他们排序(这个做法可以参考官方题解)。如果不排序,我们可以考虑看看四个点之间满足什么性质呢?如果要组成正方形,那么这四个点之中任意两个点之间的距离只会有两种情况,一种是正方形的边长,一种是正方形的对角线。这样我们就可以用一个hashset记录每两点间的距离。如果最后hashset里面的结果超过两种,或者hashset里面存在0,则一定无法组成正方形。判断hashset里面是否存在0的用意是有可能四个点只能组成一条边,类似下面这个case。

时间O(1)

空间O(1)

Java实现

 1 class Solution {
 2     public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
 3         HashSet<Integer> set = new HashSet<>(Arrays.asList(distance(p1, p2), distance(p1, p3), distance(p1, p4),
 4                 distance(p2, p3), distance(p2, p4), distance(p3, p4)));
 5         return !set.contains(0) && set.size() == 2;
 6     }
 7 
 8     private int distance(int[] a, int[] b) {
 9         return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]);
10     }
11 }

 

相关题目

593. Valid Square

939. Minimum Area Rectangle - 也是涉及找对角线的数学题

LeetCode 题目总结

posted @ 2020-11-12 02:10  CNoodle  阅读(184)  评论(0编辑  收藏  举报