1. 程式人生 > 其它 >LC447-迴旋鏢數量

LC447-迴旋鏢數量

447. 迴旋鏢的數量

計數問題,列舉i,統計與i座標不同距離的座標個數(雜湊表儲存),然後排列組合求結果。

假設有 \(m\) 個點到 \(points[i]\)距離相同,我們需要從這 $ m$個點中選擇2個點作為另外兩個點,由於考慮順序,結果為 \(A_{m}^{2} = m *(m-1)\)

據此,我們可以遍歷 \(points\),計算並統計所有點到 \(points[i]\) 的距離,將每個距離的出現次數記錄在雜湊表中,然後遍歷雜湊表,並用上述公式計算並累加回旋鏢的個數。

class Solution {
public:
    int dist(int i, int j, vector<vector<int>>& p){
        return (p[i][0] - p[j][0]) * (p[i][0] - p[j][0])  + (p[i][1] - p[j][1]) * (p[i][1] - p[j][1]);
    }
    int numberOfBoomerangs(vector<vector<int>>& points) {
        int res = 0, n = points.size();
        for(int i = 0; i < n; ++i){
            unordered_map<int,int>cnt;
            for(int j = 0; j < n; ++j) ++cnt[dist(i, j, points)];
            for(auto [_,v] : cnt)res += v * (v - 1);
        }
        return res;
    }
};