zoukankan      html  css  js  c++  java
  • 【leetcode】447 Number of Boomerangs

    题目说明

    https://leetcode-cn.com/problems/number-of-boomerangs/description/
    给定平面上 n 对不同的点,“回旋镖” 是由点表示的元组 (i, j, k) ,其中 i 和 j 之间的距离和 i 和 k 之间的距离相等(需要考虑元组的顺序)。找到所有回旋镖的数量。

    解法1

    使用unordered_map。
    第一层循环来遍历i的值
    第二层循环,要找到所有与i的距离与对应次数
    unordered_map来保存每种距离的平方与对应次数
    次数times大于等于2的则有回旋镖。
    第一个点可能性为times,第二个点可能性times - 1,则最终的数量为times * (times - 1)
    时间复杂度:O(n^2)

    int numberOfBoomerangs(vector<pair<int, int>>& points) {
        int count = 0;
        unordered_map<double,int> m;
        for (int i = 0; i < points.size(); i ++)
        {
            for (int j = 0;j < points.size(); j ++)
            {
                if (j != i)
                {
                    //以距离的平方为键,次数为值
                    double var = pow(points[j].first - points[i].first,2)+pow(points[j].second - points[i].second,2);
                    m[var]++;
                }
            }
            auto iter=m.begin();
            while(iter!=m.end())
            {
                if ((*iter).second >= 2)
                    count += (iter->second) * (iter->second - 1);//第一个点可能性为second,第二个点可能性second - 1
                iter++;
            }
            m.clear();
        }
    
        return count;
    }
    

    解法2

    保存所有距离,并作排序。若距离连续都相等,则为所要找的匹配次数,计算总数
    时间复杂度:O(n^2)

    int numberOfBoomerangs(vector<pair<int, int>>& points) {
        int res = 0;
        vector<double> dis(points.size(),0);
        for (int i = 0; i < points.size(); i ++)
        {
            //取出本轮所有距离的值
            for (int j = 0;j < points.size(); j ++)
            {
                dis[j] = pow(points[j].first - points[i].first,2)+pow(points[j].second - points[i].second,2);
            }
            //对距离作排序
            sort(dis.begin(),dis.end());
            int matchcount = 1;
            for (int j = 1;j < points.size(); j ++)
            {
                if (dis[j] == dis[j - 1]){//距离相等
                    matchcount += 1;
                }else{//距离不相等时,对相等距离计算总数
                    res += matchcount * (matchcount - 1);
                    matchcount = 1;
                }
            }
            //对于最后几个数据距离都相等的处理
            res += matchcount * (matchcount - 1);
        }
    
        return res;
    }
  • 相关阅读:
    Intersecting Lines (计算几何基础+判断两直线的位置关系)
    Morley's Theorem (计算几何基础+向量点积、叉积、旋转、夹角等+两直线的交点)
    TOYS(计算几何基础+点与直线的位置关系)
    Berland National Library
    PAT L2-017. 人以群分
    6.9服务与主机之间的映射
    第六章 部署
    5.12.1再试一次
    第5章 分解单块系统
    4.14.6 —种混合方式
  • 原文地址:https://www.cnblogs.com/JesseTsou/p/9528234.html
Copyright © 2011-2022 走看看