1
class Solution {
2
// This method returns true if the given 4 points form a square, false otherwise
3
public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
4
// We use a set to store the distances between the points
5
Set<Integer> set = new HashSet();
6
// Calculate the distances between all pairs of points and add them to the set
7
set.add(distanceSquare(p1, p2));
8
set.add(distanceSquare(p1, p3));
9
set.add(distanceSquare(p1, p4));
10
set.add(distanceSquare(p2, p3));
11
set.add(distanceSquare(p2, p4));
12
set.add(distanceSquare(p3, p4));
13
// A square must have 4 equal sides, so the set must contain 2 different values (the lengths of
14
// the sides and the diagonals)
15
// The set should not contain 0, as that would mean that two points have the same coordinates
16
return !set.contains(0) && set.size() == 2;
17
}
18

19
// This method calculates the distance between two points and returns its square
20
private int distanceSquare(int[] a, int[] b) {
21
// We use the Pythagorean theorem to calculate the distance between the points
22
return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]);
23
}
24
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0