问题:
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:
- All the input integers are in the range [-10000, 10000].
- A valid square has four equal sides with positive length and four equal angles (90-degree angles).
- Input points have no order.
解决:
① 判断给定的四个点能否组成正方形。这四个坐标是乱序的,因此你无法确定哪两个坐标处于对角线位置。
计算两两坐标之间的距离,并将它们存储起来,如果是正方形应当只有两种长度的距离,以此为判断正方形的根据。注意判断距离为0的情况。
class Solution { //32ms
public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
Set<Integer> set = new HashSet<>();
int d1 = getDistance(p1,p2);
int d2 = getDistance(p1,p3);
int d3 = getDistance(p1,p4);
int d4 = getDistance(p2,p3);
int d5 = getDistance(p2,p4);
int d6 = getDistance(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;
}
public int getDistance(int[] x,int[] y){
return (int)(Math.pow(x[0] - y[0],2) + Math.pow(x[1] - y[1],2));
}
}
② 在discuss中看到的。。。
class Solution { //19ms
public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
if(isEquals(p1,p2) || isEquals(p1,p3) || isEquals(p1,p4) || isEquals(p2,p3)
|| isEquals(p2,p4) || isEquals(p3,p4)) return false;
if(getDistance(p1,p2) != getDistance(p1,p3) && getDistance(p1,p2) != getDistance(p1, p4) && getDistance(p1,p3) != getDistance(p1, p4))
return false;
else{
if((getDistance(p1,p2) == 2 * getDistance(p1,p3) && getDistance(p1,p2) == 2 * getDistance(p2,p4))
|| (getDistance(p1,p4) == 2 * getDistance(p1,p2) && getDistance(p1,p4) == 2 * getDistance(p4,p3))
|| (getDistance(p1,p3) == 2 * getDistance(p1,p4)) && getDistance(p1,p3) == 2 * getDistance(p3,p2))
return true;
else
return false;
}
}
public int getDistance(int[] p1, int[] p2){
return (p1[0] - p2[0])*(p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]);
}
public boolean isEquals(int[] p1, int[] p2){
if(p1[0] == p2[0] && p1[1] == p2[1])
return true;
else
return false;
}
}