Givennpoints in the plane that are all pairwise distinct, a "boomerang" is a tuple of points(i, j, k)such that the distance betweeniandjequals the distance betweeniandk(the order of the tuple matters).

Find the number of boomerangs. You may assume thatnwill be at most 500 and coordinates of points are all in the range [-10000, 10000](inclusive).

这题有点类似max points on a line,至少我的思路是这样,但是似乎运行很慢,可以AC,但是只击败了2%的用户。不过似乎搜出来的其他答案思路也是一样的,时间复杂度上没有区别。

class Solution {
    public int numberOfBoomerangs(int[][] points) {
        if(points == null || points.length < 3)
            return 0;

        HashMap<Integer, HashMap<Integer, Integer>> map = new HashMap<>();
        for(int i = 0; i < points.length; i++) {
            for(int j = i + 1; j < points.length; j++) {
                if(!map.containsKey(i)) {
                    map.put(i, new HashMap<Integer, Integer>());
                }
                if(!map.containsKey(j)) {
                    map.put(j, new HashMap<Integer, Integer>());
                }

                int distSquare = (points[i][0] - points[j][0]) * (points[i][0] - points[j][0]) + (points[i][1] - points[j][1]) * (points[i][1] - points[j][1]);

                if(!map.get(i).containsKey(distSquare)) {
                    map.get(i).put(distSquare, 1);
                } else {
                    map.get(i).put(distSquare, 1 + map.get(i).get(distSquare));
                }

                if(!map.get(j).containsKey(distSquare)) {
                    map.get(j).put(distSquare, 1);
                } else {
                    map.get(j).put(distSquare, 1 + map.get(j).get(distSquare));
                }
            }
        }

        int res = 0;
        for(Map.Entry<Integer, HashMap<Integer, Integer>> entry: map.entrySet()) {
            for(Map.Entry<Integer, Integer> e: entry.getValue().entrySet()) {
                int n = e.getValue();

                res += n * (n - 1);
            }
        }

        return res;
    }
}

results matching ""

    No results matching ""