本文最后更新于:2021年2月5日 晚上
给定平面上 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:
提示:
n == points.length
1 <= n <= 500
points[i].length == 2
-104 <= xi, yi <= 104
- 所有点都 互不相同
Solution
参考 @liuyubobobo 、@suukii
- 哈希表
- 记录每个点到其他点的距离保存到哈希表中,并计算每个点的回旋镖个数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public: int numberOfBoomerangs(vector<vector<int>>& points) { int res=0; for(int i=0; i<points.size(); ++i){ unordered_map<int,int> record; for(int j=0; j<points.size(); ++j){ if(j!=i) record[dis(points[i],points[j])] += 1; } for(auto iter=record.begin(); iter!=record.end(); ++iter){ res += (iter->second) * (iter->second -1); } } return res; } private: int dis(const vector<int> &pa, const vector<int> &pb){ return pow((pa[0]-pb[0]), 2)+pow((pa[1]-pb[1]),2); } };
|