一、题目
给定平面上 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]]
二、题解思路
- 题解思路:使用unordered_map,遍历points数组,对于每一个点,从当前位置开始往后计算每一个点与其的距离,将距离和此种距离的数量存到unordered_map中,完成一个单词的此种遍历,然后计算回旋镖的数量叠加到result上。
三、代码实现
- C++代码实现
class Solution {
public:
int numberOfBoomerangs(vector<vector<int>>& points)
{
int result = 0;
unordered_map<int,int> nums; //使用unordered_map关联容器,保存关键字-值对的容器,不允许关键字重复
for(int i = 0;i<points.size();i++)
{
for(int j = 0;j<points.size();j++)
{
if(i == j)
continue;
int sum = (points[i][0]-points[j][0])* (points[i][0]-points[j][0])+
(points[i][1]-points[j][1])*(points[i][1]-points[j][1]);
nums[sum]++;
}
for(auto c:nums)
result += c.second*(c.second-1);
nums.clear();
}
return result;
}
};