目录结构
1.题目
给定平面上 n 对不同的点,“回旋镖” 是由点表示的元组 (i, j, k) ,其中 i 和 j 之间的距离和 i 和 k 之间的距离相等(需要考虑元组的顺序)。
找到所有回旋镖的数量。你可以假设 n 最大为 500,所有点的坐标在闭区间 [-10000, 10000] 中。
示例:
输入:
[[0,0],[1,0],[2,0]]
输出:
2
解释:
两个回旋镖为 [[1,0],[0,0],[2,0]] 和 [[1,0],[2,0],[0,0]]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-boomerangs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
使用Map记录和当前点有着同距离的点的个数,考虑到顺序,故使用排列规则,即n个数取2个数可形成排列n*(n-1)种。
public class Solution447 {
@Test
public void test447() {
int[][] points = {{0, 0}, {1, 0,}, {2, 0}};
System.out.println(numberOfBoomerangs(points));
}
public int numberOfBoomerangs(int[][] points) {
int result = 0;
Map<Double, Integer> map = new HashMap<>();
for (int i = 0; i < points.length; i++) {
for (int j = 0; j < points.length; j++) {
if (i == j) {
continue;
}
double t = Math.pow(points[i][0] - points[j][0], 2) + Math.pow(points[i][1] - points[j][1], 2);
map.put(t, map.getOrDefault(t, 0) + 1);
}
for (int n : map.values()) {
result += n * (n - 1);
}
map.clear();
}
return result;
}
}
- 时间复杂度:
- 空间复杂度: