LeetCode——Number of Boomerangs

Question

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

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

解题思路

注意这道题只需要求有多少对,没有具体要求是哪些,所以可以只记录点之间的距离。可以考虑用一个hash table记录每一个点到其他所有点的距离,如果相同距离数目大于等于2, 那么必有满足要求的组合。就是最后的时候注意如何求这样的组合。假如距离为6的点对是a, 那么这样的对数就是: (a * (a - 1) / 2) * 2.

具体实现

#include <iostream>
#include <vector>
#include <map> using namespace std; class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
int res = 0; for (int i = 0; i < points.size(); i++) {
map<int, int> dis_map; for (int j = 0; j < points.size(); j++) {
if (i != j) {
int dis = distance(points[i], points[j]);
dis_map[dis]++;
}
} for (map<int, int>::iterator it = dis_map.begin(); it != dis_map.end(); it++) {
res += (it->second * (it->second - 1) / 2) * 2;
}
} return res;
}
int distance(pair<int, int>& a, pair<int, int>& b) {
int x = (a.first - b.first) * (a.first - b.first);
int y = (a.second - b.second) * (a.second - b.second);
return x + y;
}
};

最新文章

  1. Apache Storm源码阅读笔记
  2. mapreduce性能提升2
  3. ffmpeg编译参数详解
  4. contiki学习笔记---process结构体
  5. Elasticsearch聚合 之 Ip Range IP地址范围聚合
  6. android xml 布局错误(黑掉了)Missing styles. Is the correct theme chosen for this layout?
  7. matlab figure 窗口最大化
  8. SQL语句创建数据库,SQL语句删除数据库,SQL语句创建表,SQL语句删除表,SQL语句添加约束,SQL语句删除约束
  9. 配置Nginx服务
  10. hdu2847(暴力)
  11. 面试之SQL(1)--选出选课数量&gt;=2的学号
  12. http://phantomjs.org/page-automation.html
  13. __m128i的理解[转]
  14. Python实战之列表list的详细简单练习2
  15. PHP PDF文件上传
  16. xcrun: error: unable to find utility &quot;PackageApplication&quot;, not a developer tool or in PATH
  17. 【redis】3.Spring 集成注解 redis 项目配置使用
  18. ELK之使用filebeat的多行过滤插件把多行合并成一行
  19. loj6089 小 Y 的背包计数问题
  20. Chart.js 学习笔记

热门文章

  1. [USACO5.5]隐藏口令Hidden Password
  2. Alcor(安国)AU6387量产修复(u盘修复)
  3. 使用数组初始化list
  4. pop 在列表中和字典中的区别
  5. win64系统丢失d3dx9d_40.dll问题
  6. python逆向工程:通过代码生成类图
  7. DBCC SHRINKFILE收缩日志/收缩数据库/收缩文件
  8. Harbor实现容器镜像仓库的管理和运维
  9. DL for objection detection
  10. Nodejs关闭windows服务进程