[LeetCode] 447、回旋镖的数量

题目描述

给定平面上 n 对不同的点,“回旋镖” 是由点表示的元组 (i, j, k) ,其中 ij 之间的距离和 ik 之间的距离相等(需要考虑元组的顺序)。找到所有回旋镖的数量。你可以假设 n 最大为 500,所有点的坐标在闭区间 [-10000, 10000] 中。

输入: [[0,0],[1,0],[2,0]]
输出: 2
解释: 两个回旋镖为 [[1,0],[0,0],[2,0]] 和 [[1,0],[2,0],[0,0]]

解题思路

思路:尝试把每一个点都当做第一个点,然后计算与其它点的距离,并将“距离”及其“出现次数”都保存在hashMap中,若计算出的距离在hashMap中已有值,则表明之前有相同的距离,此时可以将此距离的“出现次数”累加到res,由于可以换位,则“出现次数”应该先乘以2后再加到res。当前点作为第一个点结束之后,清空hashMap,继续以下一个点作为第一个点,计算过程同上。(我的实现)

参考代码

class Solution {
public:
    int numberOfBoomerangs(vector<vector<int>>& points) {
        unordered_map<int, int> umap;
        int res = 0;
        for(int i = 0; i < points.size(); i++){
            umap.clear();
            for(int j = 0; j < points.size(); j++){
                if(j == i)
                    continue;
                
                int dist = (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(umap.count(dist) > 0)
                    res += umap[dist] * 2;
                
                umap[dist]++;
            }
        }
        
        return res;
    }
    
};
发布了390 篇原创文章 · 获赞 576 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/ft_sunshine/article/details/103864282