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 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:
2

Explanation:
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距离。

注意

数据规模为500,算法复杂度选择应该是O(n^2)的
符合条件的三元组顺序(i,j,k)和(i,k,j)
通过距离公式求距离,会涉及到开根号为浮点数,查找表又是精确查找,所以在求距离的时候不开根号
求平方和的过程中可能会造成int类型溢出。该题规定了取值范围两点之间的最大距离就是20000^2+20000^2,并没有溢出

思路

这个的重点在选择什么作为键,什么作为值
通过分析我们知道,i是一个“枢纽“,对于每个i,遍历其余点到i的距离
也就是以距离为键,该距离出现的频次为值,表示到i点等于该距离的点有多少
这里写图片描述

代码

class Solution {
public:
    int numberOfBoomerangs(vector<pair<int, int>>& points) {
        int res = 0;
        for (int i = 0; i < points.size();i++)
        {       
            //对点i,统计其余点到i的距离
            unordered_map<int, int> dismap;
            int distance;
            for (int j = 0; j < points.size();j++)
            {
                if (i!=j)
                {
                    int y = points[i].second - points[j].second;
                    int x = points[i].first - points[j].first;
                    int dis = y*y + x*x;
                    dismap[dis]++;
                }
            }
            //对于距离频次大于2,(j,k)选择的可能
            for (auto iter = dismap.begin(); iter != dismap.end();iter++)
            {
                if (iter->second>=2)
                {
                    res += (iter->second * (iter->second - 1));
                }
            }
        }
        return res;
    }
};

结果

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值