Given the coordinates of four points in 2D space, return whether the four points could construct a square.java
The coordinate (x,y) of a point is represented by an integer array with two integers.ide
Example:spa
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] Output: True
Note:code
給定四個點的座標,判斷這四個點可否組成正方形。排序
按照x座標從小到大、y座標從小到大的優先級進行排序,記此時四個點爲a、b、c、d,若是能造成正方形,那麼四條邊分別是ab、ac、bd、cd。只要判斷四條邊是否相等,以及對角線是否相等便可(須要先排除全部點在一個位置這一特殊狀況)。input
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; } }