1. 程式人生 > >[LeetCode] Number of Boomerangs 迴旋鏢的數量

[LeetCode] 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]]

這道題定義了一種類似迴旋鏢形狀的三元組結構,要求第一個點和第二個點之間的距離跟第一個點和第三個點之間的距離相等。現在給了我們n個點,讓我們找出迴旋鏢的個數。那麼我們想,如果我們有一個點a,還有兩個點b和c,如果ab和ac之間的距離相等,那麼就有兩種排列方法abc和acb;如果有三個點b,c,d都分別和a之間的距離相等,那麼有六種排列方法,abc, acb, acd, adc, abd, adb,那麼是怎麼算出來的呢,很簡單,如果有n個點和a距離相等,那麼排列方式為n(n-1),這屬於最簡單的排列組合問題了,我大天朝中學生都會做的。那麼我們問題就變成了遍歷所有點,讓每個點都做一次點a,然後遍歷其他所有點,統計和a距離相等的點有多少個,然後分別帶入n(n-1)計算結果並累加到res中,只有當n大於等於2時,res值才會真正增加,參見程式碼如下:

class Solution {
public:
    int numberOfBoomerangs(vector<pair<int, int>>& points) {
        int res = 0;
        for (int i = 0; i < points.size(); ++i) {
            unordered_map<int, int> m;
            for (int j = 0; j < points.size(); ++j) {
                
int a = points[i].first - points[j].first; int b = points[i].second - points[j].second; ++m[a * a + b * b]; } for (auto it = m.begin(); it != m.end(); ++it) { res += it->second * (it->second - 1); } } return res; } };

參考資料: