447. Number of Boomerangs

weixin_34253539發表於2017-02-14

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;
    }
}

相關文章