forked from forging2012/JavaArithmetic
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode447.java
More file actions
40 lines (32 loc) · 1.24 KB
/
Leetcode447.java
File metadata and controls
40 lines (32 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package LeetCode;
import java.util.HashMap;
public class Leetcode447 {
// 447. Number of Boomerangs
// https://leetcode.com/problems/number-of-boomerangs/description/
// 时间复杂度: O(n^2)
// 空间复杂度: O(n)
public int numberOfBoomerangs(int[][] points) {
int res = 0;
for( int i = 0 ; i < points.length ; i ++ ){
// record中存储 点i 到所有其他点的距离出现的频次
HashMap<Integer, Integer> record = new HashMap<Integer, Integer>();
for(int j = 0 ; j < points.length ; j ++)
if(j != i){
// 计算距离时不进行开根运算, 以保证精度
int dis = dis(points[i], points[j]);
if(record.containsKey(dis))
record.put(dis, record.get(dis) + 1);
else
record.put(dis, 1);
}
for(Integer dis: record.keySet())
res += record.get(dis) * (record.get(dis) - 1);
}
return res;
}
// 两点之间的距离
private int dis(int[] pa, int pb[]){
return (pa[0] - pb[0]) * (pa[0] - pb[0]) +
(pa[1] - pb[1]) * (pa[1] - pb[1]);
}
}