447. Number of Boomerangs

Posted tobeabetterpig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了447. Number of Boomerangs相关的知识,希望对你有一定的参考价值。

Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).
Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive).
Example:?
Input:
[[0,0],[1,0],[2,0]]

Output:
2

Explanation:
The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]






For each point, compute the distance to the rest of the points and count.
if there are k points that have the same distance to current point, then there are P(k,2) = k*k-1 Boomerangs.
for example, p1, p2, p3 have the same distance to p0, then there are P(3,2) = 3 * (3-1) = 6 Boomerangs
(p1, p0, p2), (p1, p0, p3)
(p2, p0, p1), (p2, p0, p3)
(p3, p0, p1), (p3, p0, p2)



http://javatutorialhq.com/java/util/hashmap-class/getordefault-method-example/


On this document we will be showing a java example on how to use the getOrDefault() method of HashMap Class. Basically this method is to return a default value whenever the value was not found using the key specified on the HashMap. This is a convenient way to handle the scenario where we want a returned other than null which is being returned by get method whenever the key was not found on the HashMap object.


Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet())
{
    System.out.println(entry.getKey() + "/" + entry.getValue());
}




class Solution {
    public int numberOfBoomerangs(int[][] points) {
        int res = 0;
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < points.length; i++){
            for(int j = 0; j < points.length; j++){
                if(i == j) continue;
                int d = getDistance(points[i], points[j]);
                map.put(d, map.getOrDefault(d, 0) + 1);
            }
            for(int val : map.values()){
                res += val * (val - 1);
            }
            map.clear();
        }
        return res;
        
    }
    private int getDistance(int[] a, int[] b){
        int dx = a[0] - b[0];
        int dy = a[1] - b[1];
        return dx * dx + dy * dy;
    }
}







// a b c d e f s d e 

// a b c d e f s d e 

// a:      2 4 3
    
// freq    1 3 2 
    


// Time complexity:  O(n^2)
// Space complexity: O(n)

 

以上是关于447. Number of Boomerangs的主要内容,如果未能解决你的问题,请参考以下文章

447. Number of Boomerangs

447. Number of Boomerangs

447. Number of Boomerangs

LeetCode 447 Number of Boomerangs

leetcode447-Number of Boomerangs

[LeetCode]447 Number of Boomerangs