447. Number of Boomerangs(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83105634

题目:

Givenn points in the plane that are all pairwise distinct, a “boomerang” is a tuple of points (i, j, k)such that the distance betweeniand jequals 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来做,双重循环,对于一个固定的i,记录和它距离为L的其他点j的个数,那么对于这个i,如果某个距离中点的个数大于1m),就可以在这m个点中选择两个点和这个点i组合,i点就在第一个位置,选择出的两个点在第二个和第三个位置随机选择,则对于点 iL距离,一共有 A(m,2)种选择方式,A(m,2)=m*(m-1)

python代码:

class Solution(object):
    def numberOfBoomerangs(self, points):
        """
        :type points: List[List[int]]
        :rtype: int
        """
        result=0
        def calDistance(p1,p2):
            return pow(p1[0]-p2[0],2)+pow(p1[1]-p2[1],2)
        for i in xrange(len(points)):
            dic={}
            for j in xrange(len(points)):
                L=calDistance(points[i],points[j])
                dic[L]=dic.get(L,0)+1
            for k in dic.values():
                if k>1:
                    result+=k*(k-1)
        return result    

c++代码:

#include<cmath>
#include<map>
using namespace std;
class Solution {
public:
    int numberOfBoomerangs(vector<pair<int, int>>& points) {
        int result=0;
        for(int i=0;i<points.size();i++)
        {
            map<int,int>_map;
            for(int j=0;j<points.size();j++)
            {
                int dis=distance(points[i],points[j]);
                _map[dis]+=1;
            }
            for(auto &item:_map)
            {   int m=item.second;
                if (m>1)
                    result+=m*(m-1);
            }
        }
        return result;
    }
    int distance(pair<int,int>point1,pair<int,int>point2)
    {
        return pow(point1.first-point2.first,2)+pow(point1.second-point2.second,2);
    }
};

总结:
学会stl中pair<>的用法,学会用最简便的方法遍历字典。

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/83105634