mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 447. Number of Boomerangs.md
This commit is contained in:
parent
f0d6255bcd
commit
621a8c08af
31
447. Number of Boomerangs.md
Normal file
31
447. Number of Boomerangs.md
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
# [447. Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs/description/)
|
||||||
|
# 思路
|
||||||
|
这道题定义了一种类似回旋镖形状的三元组结构,要求第一个点和第二个点之间的距离跟第一个点和第三个点之间的距离相等。
|
||||||
|
现在给了我们n个点,让我们找出回旋镖的个数。那么我们想,如果我们有一个点a,还有两个点b和c,如果ab和ac之间的距离相等,那么就有两种排列方法abc和acb;
|
||||||
|
如果有三个点b,c,d都分别和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;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user