Number of Boomerangs问题及解法

来源:互联网 发布:从零开始学法语软件 编辑:程序博客网 时间:2024/06/01 20:23

问题描述:

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).

示例:

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]]
问题分析:

本题要求两个点到某一点的距离相同,根据题意,我们可以固定一个点i,遍历i之后的点j,计算i与j的距离,存储到map中,并记录好每个距离的出现的次数。每次遍历完成,根据排列组合方式求解即可。


过程详见代码:

class Solution {public:    int numberOfBoomerangs(vector<pair<int, int>>& points) {         int res = 0;        for (int i = 0; i < points.size(); ++i) {        unordered_map<long, int> group(points.size());// c++新特性         for (int j = 0; j < points.size(); ++j) {            if (j == i) continue;                int dy = points[i].second - points[j].second;            int dx = points[i].first - points[j].first;            int key = dy * dy;            key += dx * dx;            ++group[key];        }                for (auto& p : group) {            if (p.second > 1) {                 res += p.second * (p.second - 1);            }        }    }        return res;    }};


0 0
原创粉丝点击