您的位置:首页 > 其它

LeetCode 447. Number of Boomerangs

2016-11-26 19:34 302 查看
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]]


用HashTable。每次根据一个点,选出其余的点到这个点的距离,然后算出所有的排列数。

public class Solution {
public int distance(int[] a, int[] b){
int x = a[0] - b[0];
int y = a[1] - b[1];
return x * x + y * y;
}
public int numberOfBoomerangs(int[][] points) {
int i;
int j;
int dist;
int count = 0;
for(i = 0; i < points.length; i ++){
Map map = new HashMap();
for(j = 0; j < points.length; j ++){
if(j == i) continue;
dist = distance(points[i], points[j]);
Object o = null;
if(map.containsKey(dist)) o = map.get(dist);
else o = 0;
int b = Integer.parseInt(o.toString());
map.put(dist, ++b);
}
Set keySet = map.keySet();
Iterator it = keySet.iterator();
while(it.hasNext()){
Object key = it.next();
Object value = map.get(key);
int b = Integer.parseInt(value.toString());
if(b >= 2) count += b * (b - 1);
}
}
return count;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: