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