​LeetCode刷题实战447:回旋镖的数量

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 回旋镖的数量,我们先来看题面:

https://leetcode-cn.com/problems/number-of-boomerangs/

You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. 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).

Return the number of boomerangs.

给定平面上 n 对 互不相同 的点 points ,其中 points[i] = [xi, yi] 。回旋镖 是由点 (i, j, k) 表示的元组 ,其中 i 和 j 之间的距离和 i 和 k 之间的欧式距离相等(需要考虑元组的顺序)。

返回平面上所有回旋镖的数量。

示例

示例 1:
输入:points = [[0,0],[1,0],[2,0]]

输出:2
解释:两个回旋镖为 [[1,0],[0,0],[2,0]] 和 [[1,0],[2,0],[0,0]]

示例 2:
输入:points = [[1,1],[2,2],[3,3]]
输出:2

示例 3:
输入:points = [[1,1]]
输出:0

解题

将每个点作为第一个点进行遍历,并统计相同距离的点个数;

每个距离作为键,点个数作为值,故而采用哈希表的方式进行存储;

如果存在n个点与某一点的距离相等,则由排列组合可得n*(n-1)种排列方式,即存在n*(n-1)种回旋镖

class Solution {
    public static int numberOfBoomerangs(int[][] points) {
        int len=points.length;
        int res=0;
        HashMap<Integer,Integer> hashMap=new HashMap<Integer,Integer>();
        for(int i=0;i<len;i++){
            for(int j=0;j<len;j++){
                if(i!=j){
                    int x=points[i][0]-points[j][0];
                    int y=points[i][1]-points[j][1];
                    int dist=x*x+y*y;
                    if(hashMap.containsKey(dist)){
                        hashMap.put(dist,hashMap.get(dist)+1);
                    }else{
                        hashMap.put(dist,1);
                    }
                }
            }
            for(Integer count:hashMap.values()){
                res+=count*(count-1);
            }
            hashMap.clear();
        }
        return res;
    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-440题汇总,希望对你有点帮助!

LeetCode刷题实战441:排列硬币

LeetCode刷题实战442:数组中重复的数据

LeetCode刷题实战443:压缩字符串

LeetCode刷题实战444:序列重建

LeetCode刷题实战445:两数相加 II

LeetCode刷题实战446:等差数列划分 II - 子序列

40a59de34dd2ef2593b97c670cd221d6.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序IT圈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值