LeetCode 447 Number of Boomerangs


Problem:

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 iand 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]]

Summary:

定義一種類似“回形標”的三元組結構,即在三元組(i, j, k)中i和j之間的距離與i和k之間的距離相等。找到一組坐標數據中,可構成幾組這樣的“回形標”結構。

Analysis:

若在一組點集{a, b, c, d, ...}中,以點a為一個端點,與dis(a, b)相等的點存在n個(包含點b),那么在這n個點中任意選出兩個點與點a構成三元組,則有n(n - 1) / 2種情況。但因為三元組[a, b, c]與三元組[a, c, b]並不相同,所以實際為排列問題,答案為n(n - 1)。

代碼中正是以此為基本思想,找到以每一個點為端點時,與其余點共組成多少種不同的距離,此處用map記錄,key為距離長度,value為距離出現次數。再根據前面的公式計算即可。

 1 class Solution {
 2 public:
 3     int numberOfBoomerangs(vector<pair<int, int>>& points) {
 4         int len = points.size(), res = 0;
 5         unordered_map<int, int> m;
 6         
 7         for (int i = 0; i < len; i++) {
 8             for (int j = 0; j < len; j++) {
 9                 int x = points[i].first - points[j].first;
10                 int y = points[i].second - points[j].second;
11                 m[x * x + y * y]++;
12             }
13             
14             unordered_map<int, int> :: iterator it;
15             for (it = m.begin(); it != m.end(); it++) {
16                 int tmp = it->second;
17                 res += tmp * (tmp - 1);
18             }
19             m.clear();
20         }
21         
22         return res;
23     }
24 };


免責聲明!

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



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