题目描述
给定平面上 n 对互不相同的点 points ,其中 points[i] = [xi, yi] 。回旋镖是由点 (i, j, k) 表示的元组 ,其中 i 和 j 之间的距离和 i 和 k 之间的距离相等(需要考虑元组的顺序)。
返回平面上所有回旋镖的数量。
示例 1:
输入:points = [[0,0],[1,0],[2,0]], 输出:2
解释:两个回旋镖为 [[1,0],[0,0],[2,0]] 和 [[1,0],[2,0],[0,0]]
示例 2:
输入:points = [[1,1],[2,2],[3,3]], 输出:2
示例 3:
输入:points = [[1,1]], 输出:0
题解
遍历每个点时,开辟一个新hashmap存储所有的距离及其频率。遍历完内循环,累计每个距离对应下频率freq, 回旋镖数量 = freq * (freq - 1)。
class Solution {
public:
int numberOfBoomerangs(vector<vector<int>>& points) {
int res = 0;
for(const auto &p:points){
unordered_map<int,int> mp;
for(const auto &q:points){
int dx = p[0] - q[0];
int dy = p[1] - q[1];
mp[dx * dx + dy * dy]++;
}
//确定某一个起始点后,计算其与其他点距离,同一距离下,然后根据排列组合公式,计算回旋镖数量.
for(const auto &m:mp){
res += m.second*(m.second - 1);
}
}
return res;
}
};
复杂度分析
- 时间复杂度:O(N2),N 是数组长度。在内层循环中,寻找该点到其他点的距离时间是 O(N),计算组合数的时间是 O(m),m 是每个点到其他点的不同距离总数的最大值,m 最大值是 N-1。所以总的时间是 O(N∗(N+m)),差不多是 O(N2)。
- 空间复杂度:O(N2),需要 N 个哈希表来记录 N 个点到其他 N-1 个点的距离,最坏的情况是每个点到其他点的距离都不一样,那每个哈希表的大小就是 N-1。