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

    题目如下:

    解题思路:我首先用来时间复杂度是O(n^3)的解法,会判定为超时;后来尝试O(n^2)的解法,可以被AC。对于任意一个点,我们都可以计算出它与其余点的距离,使用一个字典保存每个距离的点的数量,例如dic[2] = 4,表示与该点距离为2的点有四个,那么这四个点任意选两个点就可以和当前点组成Boomerang,根据排列的原理,一共有4*3种方式。依次类推,进而求出当前点与所有不同距离的点组成的Boomerang的数量,最后求出所有点的Boomerang的和。

    代码如下:

    class Solution(object):
        def numberOfBoomerangs(self, points):
            """
            :type points: List[List[int]]
            :rtype: int
            """
            res = 0
            for i in range(len(points)):
                dic = {}
                for j in range(len(points)):
                    if i != j:
                        distance = (points[i][0] - points[j][0]) ** 2 + (points[i][1] - points[j][1]) ** 2
                        if distance not in dic:
                            dic[distance] = 1
                        else:
                            dic[distance] += 1
                for key,val in dic.iteritems():
                    if val <= 1:
                        continue
                    res += (val) * (val-1)
            return res
  • 相关阅读:
    mysql基础(三)
    mysql基础(二)
    Mysql基础(一)
    Less32-Less-33
    Less-27
    Less-26
    Less-25
    Less-23
    Less18-Less19
    Less13-Less-14
  • 原文地址:https://www.cnblogs.com/seyjs/p/9430697.html
Copyright © 2011-2022 走看看