给定平面上 n
对 互不相同 的点 points
,其中 points[i] = [xi, yi]
。回旋镖 是由点 (i, j, k)
表示的元组 ,其中 i
和 j
之间的距离和 i
和 k
之间的距离相等(需要考虑元组的顺序)。
返回平面上所有回旋镖的数量。
示例 1:
输入:points = [[0,0],[1,0],[2,0]] 输出:2 解释:两个回旋镖为 [[1,0],[0,0],[2,0]] 和 [[1,0],[2,0],[0,0]]
示例 2:
输入:points = [[1,1],[2,2],[3,3]] 输出:2
示例 3:
输入:points = [[1,1]] 输出:0
提示:
n == points.length
1 <= n <= 500
points[i].length == 2
-104 <= xi, yi <= 104
- 所有点都 互不相同
计数器实现。
对于每个点,计算其他点到该点的距离,然后按照距离进行分组计数。对每个组中的点进行两两排列组合(A n 取 2,即 n * (n - 1))
)计数即可。
class Solution:
def numberOfBoomerangs(self, points: List[List[int]]) -> int:
n = len(points)
if n < 3:
return 0
number = 0
for i in range(n):
distance_counter = collections.Counter()
for j in range(n):
if i == j:
continue
x1, y1 = points[i][0], points[i][1]
x2, y2 = points[j][0], points[j][1]
distance = (x1 - x2) ** 2 + (y1 - y2) ** 2
distance_counter[distance] += 1
number += sum([val * (val - 1) for val in distance_counter.values()])
return number
class Solution {
public int numberOfBoomerangs(int[][] points) {
int n = points.length;
if (n < 3) {
return 0;
}
int number = 0;
for (int i = 0; i < n; ++i) {
Map<Integer, Integer> distanceCounter = new HashMap<>();
for (int j = 0; j < n; ++j) {
if (i == j) {
continue;
}
int x1 = points[i][0], y1 = points[i][1];
int x2 = points[j][0], y2 = points[j][1];
int distance = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
distanceCounter.put(distance, distanceCounter.getOrDefault(distance, 0) + 1);
}
for (int val : distanceCounter.values()) {
number += val * (val - 1);
}
}
return number;
}
}