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]]
【问题分析】
1、这个题目很容易想到用三层循环,但是会直接超时
2、防止超时,需要进一步分析
3、由于数字对是不同,且三元组是有序的
那么,我们用大写字母标识一个数字对,一个数字对序列是[A,B,C,D,E]
当三元组是(Ai,Ai1,Ai2)时,只需要和Ai的距离相等的所有数字对任意取2个即可,
因此对每一个i,只需要计算和Ai距离相等的数字对的个数num,然后任意取2个,排列数结果为num*(num-1),
即是第i个数对是三元组中的第一个数对时,可能的boomerangs个数,
那么所有的i,numi*(numi-1)求和,即为总的boomerangs个数
【AC代码】
class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
int count = 0;
for (int i = 0; i < points.size(); ++i) {
std::map<int,int> m;
for (int j = 0; j < points.size(); ++j) {
if (i == j) {
continue;
}
int dist = distant(points[i], points[j]);
++m[dist];
}
for (std::map<int,int>::iterator iter = m.begin(); iter != m.end(); ++iter) {
count += iter->second * (iter->second - 1);
}
}
return count;
}
int distant(std::pair<int,int> point1, std::pair<int,int> point2) {
int x = point1.first - point2.first;
int y = point1.second - point2.second;
return x*x + y*y;
}
};