447. Number of Boomerangs

题目链接:https://leetcode.com/problems...

遍历每个point,然后找和它等距离的其他point,按距离来保存,比如有一个点a,和它距离都是1的点有b,c,d,那么一共的组合就有6种,包括:[a, b, c], [a, c, b], [a, b, d], [a, d, b], [a, c, d], [a, d, c]。这么算是不考重复的情况下。还有可能b, c坐标完全相同,那么b和c会被当成两个点算两次。

public class Solution {
    public int numberOfBoomerangs(int[][] points) {
        // traverse i, find the distance, keep the same distance in hashmap
        int result = 0;
        
        for(int i = 0; i < points.length; i++) {
            Map<Integer, Integer> map = new HashMap();
            for(int j = 0; j < points.length; j++) {
                if(i == j) continue;
                int dx = points[j][0] - points[i][0], dy = points[j][1] - points[i][1];
                int distance = dx * dx + dy * dy;

                map.put(distance, map.getOrDefault(distance, 0) + 1);
            }
            
            for(int k : map.keySet()) {
                int n = map.get(k);
                result += n * (n - 1);
            }
        }
        
        return result;
    }
}

lulouch13
13 声望6 粉丝