ID | Title | Difficulty | |
---|---|---|---|
Loading... |
593. Valid Square
Medium
LeetCode
Math, Geometry
Problem
Given the coordinates of four points in 2D space p1, p2, p3 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$
- $-10^4 <= x_i, y_i <= 10^4$
Code
- 对角线互相垂直平分且相等的四边形是正方形
- 邻边相等且有一个内角是直角的平行四边形是正方形
- 有一组邻边相等的矩形是正方形
- 有一个内角是直角的菱形是正方形
- 对角线相等的菱形是正方形 (四条边相等的四边形是菱形)
- 对角线互相垂直的矩形是正方形
- 有三个内角为直角且有一组邻边相等的四边形是正方形
class Solution {
public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
int[][] p = {p1, p2, p3, p4};
Arrays.sort(p, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
return getDist(p[0], p[1]) != 0
&& getDist(p[0], p[1]) == getDist(p[1], p[3])
&& getDist(p[1], p[3]) == getDist(p[3], p[2])
&& getDist(p[3], p[2]) == getDist(p[2], p[0])
&& getDist(p[0], p[3]) == getDist(p[1], p[2]);
}
public double getDist(int[] p1, int[] p2) {
return (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[0] - p1[0]) * (p2[0] - p1[0]);
}
}
按 <- 键看上一题!
592. Fraction Addition and Subtraction
按 -> 键看下一题!
594. Longest Harmonious Subsequence