LeetCode/447. Number of Boomerangs.md
2018-09-18 22:52:16 +08:00

32 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [447. Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs/description/)
# 思路
这道题定义了一种类似回旋镖形状的三元组结构,要求第一个点和第二个点之间的距离跟第一个点和第三个点之间的距离相等。
现在给了我们n个点让我们找出回旋镖的个数。那么我们想如果我们有一个点a还有两个点b和c如果ab和ac之间的距离相等那么就有两种排列方法abc和acb
如果有三个点bcd都分别和a之间的距离相等那么有六种排列方法abc, acb, acd, adc, abd, adb推广一下如果有n个点和a距离相等那么排列方式为n(n-1),这属于最简单的排列组合问题了。
那么我们问题就变成了遍历所有点让每个点都做一次点a然后遍历其他所有点统计和a距离相等的点有多少个然后分别带入n(n-1)计算结果并累加到res中。
时间复杂度O(n^2)
# C++
```
class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
unordered_map<int, int>dist_count;
int delta_x, delta_y, dist_2, res = 0;
unordered_map<int, int>::iterator it;
for(int i = 0; i < points.size(); i++){
for(int j = 0; j < points.size(); j++){
delta_x = points[i].first - points[j].first;
delta_y = points[i].second - points[j].second;
dist_2 = delta_x * delta_x + delta_y * delta_y;
dist_count[dist_2]++;
}
for(it = dist_count.begin(); it != dist_count.end(); it++)
res += (it->second * (it -> second - 1));
dist_count.clear();
}
return res;
}
};
```