447. Number of Boomerangs
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]]
题目链接:https://leetcode.com/problems/number-of-boomerangs/
解题思路
做这题的时候又鱼了,是看了学习视频才做出来的。
可以从数据范围得出结论需要一个n^2复杂度的算法,问题的关键在于查找表怎么储存。本题只需要算个数,所以只要对每个点创建一个到所有其不同点距离的个数统计。
时间复杂度:O(n^2)
空间复杂度:O(n)
class Solution {
public:
int numberOfBoomerangs(vector<vector<int>>& points) {
int res=0;
for(int i=0;i<points.size();++i){
unordered_map<double,int> record;
for(int j=0;j<points.size();++j){
if(i==j) continue;
double dist = distance(points[i],points[j]);
record[dist]++;
}
for(auto iter=record.begin();iter!=record.end();++iter){
res+=(iter->second)*(iter->second -1);
}
}
return res;
}
double distance(vector<int>a, vector<int>b){
return pow(a[0]-b[0],2)+pow(a[1]-b[1],2);
}
};

本文介绍了一种解决LeetCode上编号为447的问题——寻找平面上构成回力标形状的点组数量的方法。通过使用哈希表记录每个点与其他点之间的距离出现次数,可以有效地计算出符合回力标定义的点组数量,实现时间复杂度为O(n^2),空间复杂度为O(n)。
406

被折叠的 条评论
为什么被折叠?



