LeetCode 447 Number of Boomerangs

来源:互联网 发布:百度地图js api离线 编辑:程序博客网 时间:2024/05/16 15:19

题目:

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]]
题目链接

题意:

给定平面上所有两两不同的n个点,“boomerang”是一个点(i,j,k)的元组,使得i和j之间的距离等于i和k之间的距离(按照元组的顺序)。编写函数求boomerang的数量。

n至多为500,点的坐标都在10000, 10000(包括)范围内。

对于每一个boomerang,都存在一个中心点,即i点,枚举i点,记录i到其他个点的距离,看是否有相同的距离,假如有多个,则在其中选两个,构成组合数,2 * C(2, n),n为距离相等的数量,对于每一组,顺序都可以反转,所以需要乘两倍。

代码如下:

class Solution {public:    int numberOfBoomerangs(vector<pair<int, int>>& points) {        int ans = 0;        for (int coor = 0; coor < points.size(); coor++) {            map<long, int> dic;            for (int i = 0; i < points.size(); i ++) {                if (i == coor) continue;                int dx = points[coor].first - points[i].first;                int dy = points[coor].second - points[i].second;                dic[dx*dx + dy*dy] ++;            }             for (auto &p : dic) {                if (p.second > 1) {                    ans += p.second * (p.second - 1);                }            }        }        return ans;    }};


原创粉丝点击