leetcode 593: Valid Square

来源:互联网 发布:淘宝卖家刷单后果 编辑:程序博客网 时间:2024/06/08 16:32

要求:

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.

注意:就是判断四个坐标能否构成一个正方形,注意这四个坐标是乱序的,因此你无法确定哪两个坐标处于对角线位置。思路是计算两两坐标之间的距离,并将它们存储,如果是正方形应当只有两种长度的距离,以此为判断正方形的根据(如果坐标都为整数,那么等边三角形加上外心这种情况似乎是不会出现的,如果还有问题请指正)。注意判断距离为0的情况

public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {HashSet set = new HashSet();int d1 = distance(p1, p2);int d2 = distance(p1, p3);int d3 = distance(p1, p4);int d4 = distance(p2, p3);int d5 = distance(p2, p4);int d6 = distance(p3, p4);if (d1 == 0 || d2 == 0 || d3 == 0 || d4 == 0 || d5 == 0 || d6 == 0)return false;set.add(d1);set.add(d2);set.add(d3);set.add(d4);set.add(d5);set.add(d6);if (set.size() == 2)return true;return false;}private int distance(int[] x, int[] y) {return (int) (Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2));}



原创粉丝点击