每日一题 2024-1-8 回旋镖的数量

发布时间 2024-01-08 13:00:35作者: sunyafei

1.题目原题链接

给定平面上 n互不相同 的点 points,其中 points[i] = [xi, yi]回旋镖 是由点 (i, j, k)表示的元组 ,其中ij之间的距离和ik之间的欧式距离相等(需要考虑元组的顺序)。

返回平面上所有回旋镖的数量。

示例 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

提示

  • n == points.length
  • 1 <= n <= 500
  • points[i].length == 2
  • -104 <=xi, yi<= 104
  • 所有点都 互不相同

2.解题思路

枚举回旋镖的拐点point[i],假设point里有m个点的距离到拐点距离相等,要从m中选2个组成回旋镖,因为考虑顺序,所以说回旋镖个数为全排列$$A_m^2=m*(m-1)$$,将每个距离的出现次数记录在哈希表中,然后遍历哈希表,并用上述公式计算并累加回旋镖的个数。

3.c++代码

class Solution {
public:
    int numberOfBoomerangs(vector<vector<int>> &points) {
        int ans = 0;
        for (auto &p : points) {
            unordered_map<int, int> cnt;
            for (auto &q : points) {
                int dis = (p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1]);
                ++cnt[dis];
            }
            for (auto &[_, m] : cnt) {
                ans += m * (m - 1);
            }
        }
        return ans;
    }
};