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]]

问题分析

  • 暴力法: 三层遍历,得到 i ,j, k三个点,然后统计相应的符合规定的次数。但是注意,题目给出的数据规模 N = 500 , 上述 O(N^3) 的时间复杂度肯定会超时。
  • 给定数据规模为 N = 500 ,那么肯定是要设计一个 低于 O(N^3) 的算法的
  • 正确做法: 遍历每一个点,然后计算其他点到该点的距离,用 map 存储关于这个点的距离信息。key 存储到该点的 distance, value 存储到该点距离为 distance 的有多少个点。 然后再遍历map中的 values,累加所有个数。如到该点距离为2的点有3个,那么可以得出 3 * 2 = 6 种符合要求的组合。
  • 但有一个陷阱需要注意,那便是距离的计算
    • 因为我们不需要精确的距离,只要一种相对的概念,等于或者不等于,所以我们统计距离的平方即可。
      如果统计的是精确地距离,可以会带来以下麻烦:
      • 浮点数精度损耗问题
      • 开根号带来额外的开销
  • 计算距离平方时,同样也要注意数据规模,因为有可能数据溢出,该题根据题意,最大距离不超过 int 取值范围,所以可以用 int 存储。
  • 时间复杂度:O(N^2)

经验教训

  • 当使用查找表 map时,如何灵活选取键值 key,让问题更加方便
  • 距离计算中的浮点数精度损失问题 以及 数据溢出问题
  • 进阶题目: Leetcode 149-Max Points on a Line

代码实现

class Solution {
    public int numberOfBoomerangs(int[][] points) {
        if (points == null || points.length == 0 || points[0] == null || points[0].length == 0) {
            return 0;
        }
        int res = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < points.length; i++) {
            for (int j = 0; j < points.length; j++) {
                if (i == j) {
                    continue;
                }
                int dis = getDistance(points[i], points[j]);
                map.put(dis, map.getOrDefault(dis, 0) + 1);
            }
            // 注意如何遍历map中的values
            for (int count : map.values()) {
                res += count * (count - 1);
            }
            map.clear();
        }
        return res;
    }

    public int getDistance(int[] p1, int[] p2) {
        return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值