447. Number of Boomerangs 难度:easy
2017-01-01 20:21
405 查看
题目:
Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points
the distance between
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).
Example:
思路:
若在一组点集{a, b, c, d, ...}中,以点a为一个端点,与dis(a, b)相等的点存在n个(包含点b),因为三元组[a, b, c]与三元组[a, c, b]并不相同,所以实际为排列问题,答案为n(n - 1)。
程序:
class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
int len = points.size(), res = 0;
unordered_map<int, int> m;
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
int x = points[i].first - points[j].first;
int y = points[i].second - points[j].second;
m[x * x + y * y]++;
}
unordered_map<int, int> :: iterator it;
for (it = m.begin(); it != m.end(); it++) {
int tmp = it->second;
res += tmp * (tmp - 1);
}
m.clear();
}
return res;
}
};
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
iand
jequals
the distance between
iand
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).
Example:
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]]
思路:
若在一组点集{a, b, c, d, ...}中,以点a为一个端点,与dis(a, b)相等的点存在n个(包含点b),因为三元组[a, b, c]与三元组[a, c, b]并不相同,所以实际为排列问题,答案为n(n - 1)。
程序:
class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
int len = points.size(), res = 0;
unordered_map<int, int> m;
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
int x = points[i].first - points[j].first;
int y = points[i].second - points[j].second;
m[x * x + y * y]++;
}
unordered_map<int, int> :: iterator it;
for (it = m.begin(); it != m.end(); it++) {
int tmp = it->second;
res += tmp * (tmp - 1);
}
m.clear();
}
return res;
}
};
相关文章推荐
- html文件中flash视频格式(flv、swf)文件的嵌入方法
- 关于sscanf函数的使用
- Innodb表select查询顺序
- 哈夫曼编码C语言
- 文法G[E]分析表分析字符串(i+)-编译原理
- Redbear DUO初体验
- mysql数据库基本操作以及备份
- 2017,让奔跑开始,让冲刺变得渴望
- PQ8.05硬盘分区图文教程
- 模板方法模式---我的地盘听我的
- 20161114---手写图片转为lmdb
- 包图
- 电脑长鸣的原因分析和解决方案
- 20161114——LeNet-5预测数据-第一次跑
- WICED 开发 Redbear Duo
- socket实现UDP数据传输
- tshark----wireshark的命令行工具
- Android 开源之StickyHeaderListView 标题渐变、吸附悬停、筛选分类、动态头部
- C++'s HelloWorld
- Mysql使用技巧