題目:
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個點,“boomerang”是一個點(i,j,k)的元組,使得i和j之間的距離等於i和k之間的距離(按照元組的順序)。編寫函數求boomerang的數量。
n至多爲500,點的座標都在10000, 10000(包括)範圍內。
對於每一個boomerang,都存在一箇中心點,即i點,枚舉i點,記錄i到其他個點的距離,看是否有相同的距離,假如有多個,則在其中選兩個,構成組合數,2 * C(2, n),n爲距離相等的數量,對於每一組,順序都可以反轉,所以需要乘兩倍。
代碼如下:
class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
int ans = 0;
for (int coor = 0; coor < points.size(); coor++) {
map<long, int> dic;
for (int i = 0; i < points.size(); i ++) {
if (i == coor) continue;
int dx = points[coor].first - points[i].first;
int dy = points[coor].second - points[i].second;
dic[dx*dx + dy*dy] ++;
}
for (auto &p : dic) {
if (p.second > 1) {
ans += p.second * (p.second - 1);
}
}
}
return ans;
}
};