[LeetCode] 447. Number of Boomerangs

来源:互联网 发布:python小项目 编辑:程序博客网 时间:2024/05/23 00:49

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]]
class Solution {public:    int numberOfBoomerangs(vector<pair<int, int>>& points) {        unordered_map<long, int> comb;        int cnt = 0;        for (int i = 0; i < points.size(); i++) {            for (int j = 0; j < points.size(); j++) {                if (i == j) continue;                auto SD = SquareDistance(points[i], points[j]);                comb[SD]++;            }            for (auto &p : comb) {                int n = p.second;                cnt += n * (n - 1);            }            comb.clear();        }        return cnt;    }private:    long SquareDistance(pair<int, int> &pt1, pair<int, int> &pt2) {        int DX = pt1.first - pt2.first, DY = pt1.second - pt2.second;        return DX * DX + DY * DY;    }};
原创粉丝点击