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]]

分析:循环查找每个点, 每个点都用一个hashmap存放其他点到该点得值 作为key,i,j = i, k。有重复则value+1;

计算总共有几对是用组合 n * n-1;

public class Solution {
    public int numberOfBoomerangs(int[][] points) {
        int sum = 0;
        if(points == null || points.length == 0) return sum;
        
        for(int i = 0 ; i < points.length ; i ++){
            HashMap<Integer, Integer> map = new HashMap<>();
            for(int j = 0; j < points.length; j++){
                int dis = getDis(points[i], points[j]);
                map.put(dis, map.getOrDefault(dis,0)+1);
            }
        
        for(int value : map.values()){
            sum += value * (value - 1);   //2 combination;
        }
        map.clear();
        }
        return sum;
    }
    
    public int getDis(int[] a, int[] b){
        return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]);
    }
    
}


原文地址:https://www.cnblogs.com/joannacode/p/6101145.html