您的位置:首页 > 其它

Number of Boomerangs问题及解法

2017-04-22 09:42 393 查看
问题描述:

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).

示例:

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]]

问题分析:

本题要求两个点到某一点的距离相同,根据题意,我们可以固定一个点i,遍历i之后的点j,计算i与j的距离,存储到map中,并记录好每个距离的出现的次数。每次遍历完成,根据排列组合方式求解即可。

过程详见代码:

class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
int res = 0;

for (int i = 0; i < points.size(); ++i) {
unordered_map<long, int> group(points.size());// c++新特性
for (int j = 0; j < points.size(); ++j) {
if (j == i) continue;

int dy = points[i].second - points[j].second;
int dx = points[i].first - points[j].first;
int key = dy * dy;
key += dx * dx;
++group[key];
}

for (auto& p : group) {
if (p.second > 1) {
res += p.second * (p.second - 1);
}
}
}

return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐