一、题目大意:
给定平面上的n个两两不同的点,一个“回飞镖”是指一组点(i, j, k)满足i到j的距离=i到k的距离(考虑顺序)
计算回飞镖的个数。你可以假设n最多是500,并且点坐标范围在 [-10000, 10000] 之内。
二、分析
1,解题思想:这道题目很简单,枚举点i(x1, y1),计算点i到各点j(x2, y2)的距离,并分类计数;利用排列组合知识,从每一类距离中挑选2个点的排列数 A(n, 2) = n * (n - 1);将上述结果累加即为最终答案
2,我们一般是用map去统计计数的,但是涉及集合的操作都是比较慢的,所以这篇文章主要是对比快慢的。优化对map的处理。
三,java优化:
很明显,X比Y在进行map操作次数上优化了,我们在设计的时候应尽量的减少集合操作。(X85%,Y20%)
1,实现X
public static int numberOfBoomerangs(int[][] points) {
int res = 0;double distance = 0;
Map<Double, Integer> map = new HashMap<Double, Integer>();
for(int i=0;i<points.length;i++) {
for(int j=0;j<points.length;j++) {//每一个点,计数有多少相等的点
distance = Math.sqrt((points[i][0]-points[j][0])**2 + (points[i][1]-points[j][1])**2
if(map.get(distance) == null)
map.put(distance, 1);
else
map.put(distance, map.get(distance)+1);
}
for(int n : map.values()) {//相等的点,总共有多少种组合
if(n > 1) {
res += n*(n-1);
}
}
map.clear();//清空
}
return res;
}
2,实现Y
int count = 0;
int n = points.length;
// 直接统计距离过来就可以
for (int i = 0; i < n; i++) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int j = 0; j < n; j++) {
int dis = (points[i][0] - points[j][0]) * (points[i][0] - points[j][0]) + (points[i][1] - points[j][1]) * (points[i][1] - points[j][1]);
if (!map.containsKey(dis)) {
map.put(dis, 0);
}
//两个位置可以j k可以颠倒
count += map.get(dis) * 2;
map.put(dis, map.get(dis) + 1);
}
}
return count;
四、python优化
迭代器遍历,比直接遍历要快。
1,实现一
class Solution(object):
def numberOfBoomerangs(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
ans = 0
map = {}
for x1, y1 in points:
for x2, y2 in points:
dis = (x1 - x2) ** 2 + (y1 - y2) ** 2
if map.has_key(dis):
map[dis] += 1
else:
map[dis] = 1
for d in map.values()://迭代器访问
ans += d*(d-1)
map.clear()
return ans
2,实现二
class Solution(object):
def numberOfBoomerangs(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
ans = 0
for x1, y1 in points:
dmap = collections.defaultdict(int)
for x2, y2 in points:
dmap[(x1 - x2) ** 2 + (y1 - y2) ** 2] += 1
for d in dmap://map访问
ans += dmap[d] * (dmap[d] - 1)
return ans