Leetcode 447. Number of Boomerangs

/**
 * Using a hashmap to save the pair of <distance, count>
 * Find all 2-permutations of N, P(n, 2) = n*(n-1)
 * Increase the count when distance is already in the map.
 * Sum up the count, another 2-permutations of count.
 */ 
public class Solution {
    public int numberOfBoomerangs(int[][] points) {
        int dist = 0, ret = 0;
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        // do 2-permutations of n
        for (int i=0; i<points.length; i++) {
            for (int j=0; j<points.length; j++) {
                if (i == j) continue;
                dist = calDist(points, i, j);
                // increase count when dist is already in the map
                if (map.containsKey(dist))
                    map.put(dist, map.get(dist)+1);
                else
                    map.put(dist, 1);
            }
            // count the total number of paires
            // e.g. for record <dist1, 4>, there are total 4*3 different paires, the order of the tuple matters*
            // 1, 2, 3 and 1, 3, 2 are different
            for (int cnt : map.values())
                ret += cnt * (cnt-1);
            // starting next point
            map.clear();
        }
        
        return ret;
    }
    
    // we don't have to calculate the exactely distance between two points,
    // instead just return (x1-x2)^2+(y1-y2)^2
    public static int calDist(int[][] points, int i, int j) {
        // dist = sqrt((x1-x2)^2+(y1-y2)^2)
        int x = (points[i][0]-points[j][0]) * (points[i][0]-points[j][0]);
        int y = (points[i][1]-points[j][1]) * (points[i][1]-points[j][1]);
        return x + y;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值