LeetCode 593. Valid Square

原题链接在这里:https://leetcode.com/problems/valid-square/

题目:

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.

题解:

Sort the 4 points based on x, if x are equal, sort on y. Then find out, p0 - p3, p1 - p2 are always diagonal.

Compare 4 edge length are equal. And compare 2 diagonal legnth are equal.

Time Complexity: O(1).

Space: O(1).

AC Java: 

 1 class Solution {
 2     public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
 3         int [][] pos = new int[][]{p1, p2, p3, p4};
 4         Arrays.sort(pos, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
 5         return dist(pos[0], pos[1]) != 0 && dist(pos[0], pos[1]) == dist(pos[1], pos[3]) &&
 6             dist(pos[1], pos[3]) == dist(pos[3], pos[2]) && dist(pos[3], pos[2]) == dist(pos[2], pos[0]) &&
 7             dist(pos[0], pos[3]) == dist(pos[1], pos[2]);
 8     }
 9     
10     private long dist(int [] a, int [] b){
11         return (b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1]);
12     }
13 }
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12047639.html