[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;
    }
};

 

參考資料:

https://discuss.leetcode.com/topic/66523/c-solution-with-explanation

https://discuss.leetcode.com/topic/66521/share-my-straightforward-solution-with-hashmap-o-n-2/2

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM