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).
例如: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]]
其实就是寻找原数组中距离相同的点的个数。

思路:嵌套遍历数组两次,第一次为要计算距离的点,内循环是计算其他点到该点的距离。并使用hashMap存储距离信息。代码如下所示(本段代码击败了45%的用户):

    public int numberOfBoomerangs2(int[][] points) {
        int result = 0;
        HashMap<Integer,Integer> distMap = new HashMap<Integer,Integer>();
        for(int[] i : points) {
            for(int[] j : points) {
                if(i==j) continue;
                int dist = (i[0]-j[0])*(i[0]-j[0]) + (i[1]-j[1])*(i[1]-j[1]);
                int prevDist = distMap.containsKey(dist) ? distMap.get(dist) : 0;
                result += 2*prevDist;
                distMap.put(dist, prevDist+1);
            }
            distMap.clear();
        }
        return result;
    }

但是使用下面的代码却达到78%的胜率,二者的思路是完全相同的,不知道速度提升在哪里:

    public int numberOfBoomerangs3(int[][] p) {
        int n = p.length;
        if(n==0) return 0;
        int count = 0;
        for(int i=0;i<n;i++){
            Map<Double,Integer> map = new HashMap<>();
            for(int j=0;j<n;j++){
                if(map.containsKey(distance(p[i],p[j]))){
                    int value = map.get(distance(p[i],p[j]));
                    count+=2*value;
                    map.put(distance(p[i],p[j]),value+1);
                } else {
                    map.put(distance(p[i],p[j]),1);
                }
            }
        }
        return count;
    }

    public Double distance(int[] a, int[]b){
        return Math.sqrt(Math.pow(a[0]-b[0],2) + Math.pow(a[1]-b[1],2));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值