LeetCode 回旋镖的数量(hash表)

给定平面上 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]]

思路分析:固定i,然后计算各个点到i的距离的平方(距离有可能会出现小数,不方便处理),然后根据各种距离的平方,确定由i打头可构成的回旋镖的数量。(时间复杂度O(n2),空间复杂度O(n))

class Solution {
public:
    //计算两点之间的距离
    int twoPointDistance(pair<int, int> &onePoint, pair<int, int> &twoPoint){
        return (onePoint.first - twoPoint.first) * (onePoint.first - twoPoint.first) + (onePoint.second - twoPoint.second) * (onePoint.second - twoPoint.second);
    }
    int numberOfBoomerangs(vector<pair<int, int>>& points) {
        int pointsSize = points.size(), result = 0;
        //index标记固定第一个点i
        for (int index = 0; index < pointsSize; ++index){
            unordered_map<int, int> distanceMap;//distanceMap[dis]用于记录与points[index]距离为dis的个数
            //确认各个点到index的距离平方
            for (int j = 0; j < pointsSize; ++j){
                if (j != index){//不能包括自己
                    distanceMap[twoPointDistance(points[index], points[j])] += 1;
                }
            }
            //各种距离平方的个数,根据排列组合,A(2, n)从n中挑出两个排序
            for (auto &item : distanceMap){
                result += (item.second) *(item.second - 1);
            }
        }
        return result;
    }
};

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41855420/article/details/88869143
今日推荐