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
思路:就是每两个点的距离,要么是a要么是Sqrt(2)*a, 只能有两种值。set中不能有0,因为point有重合的点;
class Solution {
public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
if(p1 == null || p2 == null || p3 == null || p4 == null
|| p1.length <= 1 || p2.length <= 1 || p3.length <= 1 || p4.length <= 1) {
return false;
}
HashSet<Integer> set = new HashSet<Integer>();
ArrayList<int[]> list = new ArrayList<>();
list.add(p1); list.add(p2);list.add(p3);list.add(p4);
for(int i = 0; i < list.size(); i++) {
for(int j = i + 1; j < list.size(); j++) {
int dis = getDistance(list.get(i), list.get(j));
set.add(dis);
}
}
return !set.contains(0) && set.size() == 2;
}
private int getDistance(int[] p1, int[] p2) {
int x1 = p1[0];
int y1 = p1[1];
int x2 = p2[0];
int y2 = p2[1];
return (x2 - x1) * (x2 - x1) + (y2 - y1) *(y2 - y1);
}
}