美文网首页
447. Number of Boomerangs

447. Number of Boomerangs

作者: hyhchaos | 来源:发表于2016-11-25 21:56 被阅读33次

Java

public class Solution {
    public int numberOfBoomerangs(int[][] points) {
        int count=0;
        for(int i=0;i<points.length;i++)
        {
            Map<Integer,Integer> distance=new HashMap<>();
            for(int j=0;j<points.length;j++)
            {
                int dx=points[i][0]-points[j][0];
                int dy=points[i][1]-points[j][1];
                int tmp=dx*dx+dy*dy;
                if(distance.containsKey(tmp))
                {
                int m=distance.get(tmp)+1;
                distance.put(tmp,m);
                }
                else
                distance.put(tmp,1);
            }
            for(int key:distance.keySet())
            {
                int n=distance.get(key);
                if(n>1)
                {
                    count+=n*(n-1);
                }
            }
        }
        return count;
    }
}

最优解,方法一样,写得更简练

Javascript

/**
 * @param {number[][]} points
 * @return {number}
 */
var numberOfBoomerangs = function(points) {
    let res = 0;
    points.forEach(p1 => {
        const map = {};
        points.forEach(p2 => {
            const dist = Math.pow(p1[0] - p2[0], 2) + Math.pow(p1[1] - p2[1], 2);
            res += (map[dist] || 0) * 2;
            map[dist] = (map[dist] || 0) + 1;
        });
    });
    return res;
};

相关文章

网友评论

      本文标题:447. Number of Boomerangs

      本文链接:https://www.haomeiwen.com/subject/snewpttx.html