查找表类算法//回旋镖的数量

给定平面上 n 对不同的点,“回旋镖” 是由点表示的元组 (i, j, k) ,其中 i 和 j 之间的距离和 i 和 k 之间的距离相等(需要考虑元组的顺序)。

找到所有回旋镖的数量。你可以假设 n 最大为 500,所有点的坐标在闭区间 [-10000, 10000] 中。

示例:

输入:
[[0,0],[1,0],[2,0]]

输出:
2

解释:
两个回旋镖为 [[1,0],[0,0],[2,0]][[1,0],[2,0],[0,0]]
class Solution {
    private int getDistance(int[] a, int[] b){
        int dx = a[0] - b[0];
        int dy = a[1] - b[1];
        return dx*dx+dy*dy;
    }
    public int numberOfBoomerangs(int[][] points) {
        if(points == null)
            return 0;
        int res = 0;
        for(int i = 0; i < points.length; i++){
            Map<Integer,Integer> disCount = new HashMap<>();
            for(int j = 0; j < points.length; j++){
                if(i == j)
                    continue;
                int distance = getDistance(points[i], points[j]);
                int count = disCount.getOrDefault(distance,0);
                disCount.put(distance,count+1);
            }
            for(int count:disCount.values()){
            res += count*(count-1);
            }
        }
        return res;
    }
}

getOrDefault(): 当Map集合中有这个key时,就使用这个key值,如果没有就使用默认值defaultValue

class Solution {
public:
    int numberOfBoomerangs(vector<pair<int, int>>& points) {
        int res = 0;
        unordered_map<double,int> Hash;
        for(pair<int,int>p1:points){
            Hash.clear();
            for(pair<int,int>p2:points){
                if(p1 == p2)
                    continue;
                Hash[hypot(p1.first-p2.first,p1.second-p2.second)]++;
            }
            for(auto val:Hash){
                if(val.second>1)
                    res+=val.second*(val.second-1);
            }
        }
        return res;
    }
};

hypot(x,y):return x*x+y*y

原文地址:https://www.cnblogs.com/strawqqhat/p/10602380.html