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]]
===================================================================
題目鏈接:https://leetcode.com/problems/number-of-boomerangs/
題目大意:求滿足條件的三元組個數。
思路:遍歷,用unordered_map統計所有點與points[i]的距離,ans += count * (count-1)
參考代碼:
class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
int n = points.size() , ans = 0 ;
if ( n <= 2 )
return 0 ;
for ( int i = 0 ; i < n ; i ++ )
{
unordered_map <int,int> maping ;
for ( int j = 0 ; j < n ; j ++ )
{
if ( i != j )
maping[getDis(points[i],points[j])] ++ ;
}
for ( auto& x : maping )
{
int count = x.second ;
if ( count >= 2 )
ans += count * ( count - 1 ) ;
}
}
return ans ;
}
private:
int getDis ( const pair <int,int>& a , const pair <int,int>& b )
{
return pow( ( a.first - b.first ) , 2 ) + pow( ( a.second - b.second ) , 2 ) ;
}
};