leetcode刷題 447. Number of Boomerangs

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 andj 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]]
class Solution {
public:
    int numberOfBoomerangs(vector<pair<int, int>>& points) {
        int len = points.size();
        int ret = 0;
        for(int i = 0; i < len; ++i)
        {
            map<int,int> res;
            for(int j = 0; j < len; ++j)
            {
                int tmp = dis(points[i],points[j]);
                res[tmp]++;
            }
            for(map<int,int>::iterator it = res.begin(); it != res.end(); ++it)
            {
                if(it -> second >= 2)
                    ret = ret + it -> second * (it-> second - 1);
            }
        }
        return ret;
    }
    int dis(pair<int,int> a,pair<int,int> b)
    {
        int x = pow(a.first - b.first,2);
        int y = pow(a.second - b.second,2);
        return x + y;
    }
};

核心思想:

1.用map記錄下同距離的點數超過2的所有,然後對內部這些點進行排列  比如a 跟b c d 的距離都是相等的  

那麼會有  

a,b a.c   

a,b a.d

a.c a.d 

然後再調換順序  乘以2即可  其實最終就是等差數列求和乘以2  就是(n+1)*n /2 * 2  也就是n*(n + 1)  

發佈了119 篇原創文章 · 獲贊 17 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章