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
class Solution {
    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
        int[] arr = new int[]{dist(p1, p2),dist(p1, p3),dist(p1, p4),dist(p2, p3),dist(p2, p4),dist(p3, p4)};
        Arrays.sort(arr);
        return (arr[0] > 0 && arr[0] == arr[1] && arr[1] == arr[2] && arr[2] == arr[3] && arr[5] == arr[4]);
    }
    public int dist(int[] a, int[] b) {
        return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]);
    }
}

如何判断4个点能形成square?

把6条边放到数组里排序,然后让前4条相等,再让后两条相等。草

 

上一篇:【DB笔试面试593】在Oracle中,表的访问方式有哪几种?


下一篇:045医疗项目-模块四:采购单模块—采购单提交(Dao,Service,Action三层)