LeetCode No.447 Number of Boomerangs

来源:互联网 发布:easybcd怎么引导linux 编辑:程序博客网 时间:2024/06/04 17:57

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:2Explanation: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 ) ;    }};


0 0