题目
给定平面上 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]]
代码模板:
class Solution {
public int numberOfBoomerangs(int[][] points) {
}
}
分析
首先循环算出每两个点之间的距离,放入map里面,如果这个距离有的话,就把原来的计数+1,然后加上当前的计数。最后再把这个temp*2,继续去循环下一个点。
解答
class Solution {
public int numberOfBoomerangs(int[][] points) {
int len = points.length;
int count = 0;
int tempRes = 0;
int result = 0;
HashMap<Integer, Integer> hasDis = new HashMap<Integer, Integer>();
for(int i = 0;i < len ; i ++){
for(int j = 0;j<len ;j++){
int distance = (points[j][1] - points[i][1])*( points[j][1] - points[i][1])
+(points[j][0]-points[i][0])*(points[j][0]-points[i][0]);
if(distance != 0){
if(hasDis.containsKey(distance)){
count = hasDis.get(distance);
hasDis.put(distance,count+1);
tempRes = tempRes +count;
}else{
hasDis.put(distance,1);
}
}
}
result += tempRes * 2;
tempRes = 0;
hasDis.clear();
}
return result;
}
}

博客围绕平面上 n 对不同点展开,要找出所有“回旋镖”(元组 (i, j, k) ,i 和 j 、i 和 k 距离相等且考虑顺序)的数量。分析部分提出循环算出每两点距离放入 map 计数,最后将计数结果乘 2 继续循环下一个点来求解。
-java&spm=1001.2101.3001.5002&articleId=88697628&d=1&t=3&u=0b251f389b384929b59199e1b03ac368)
1万+

被折叠的 条评论
为什么被折叠?



