[抄题]:
Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k)
such that the distance between i
and j
equals the distance between i
and k
(the order of the tuple matters).
Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive).
Example:
Input: [[0,0],[1,0],[2,0]] Output: 2 Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:n^2
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
不知道怎么表示距离相等:用hashmap统计距离的出现次数
[一句话思路]:
用hashmap统计距离的出现次数,再用组合公式选2个点
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- 理解“求距离”的两点的地位是等价的。所以范围相同,都是<length
- 用getordefault的时候还是要 提前指定default类型的,稍微注意下
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
“距离相等”可以理解为“同一距离出现了两次”,用hashmap
[复杂度]:Time complexity: O(n^2 双重循环) Space complexity: O(n)
[英文数据结构或算法,为什么不用别的数据结构或算法]:
不知道距离怎么表示:a[0] - b[0], a[1] - b[1] 平方和
[关键模板化代码]:
求距离:
public int getDistance(int[] a, int[] b) { int dx = a[0] - b[0]; int dy = a[1] - b[1]; return dx * dx + dy * dy; }
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
class Solution { public int numberOfBoomerangs(int[][] points) { //cc if (points == null || points[0] == null) { return 0; } //ini hashmap HashMap<Integer, Integer> map = new HashMap<>(); int res = 0; //for loop: put into map //res += val * (val - 1) //.clear() for (int i = 0; i < points.length; i++) { for (int j = 0; j < points.length; j++) { if (i == j) continue; int d = getDistance(points[i], points[j]); map.put(d, map.getOrDefault(d, 0) + 1); } for (int val : map.values()) { res += val * (val - 1); } map.clear(); } //return res return res; } public int getDistance(int[] a, int[] b) { int dx = a[0] - b[0]; int dy = a[1] - b[1]; return dx * dx + dy * dy; } }