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

    Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals 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]]
    

    Solution1:(TLE)

    class Solution:
        def numberOfBoomerangs(self, points):
            """
            :type points: List[List[int]]
            :rtype: int
            """
            res = 0
            def compute(x,y):
                return (x[0]-y[0])**2 + (x[1]-y[1])**2
            for i in range(len(points)-2):
                for j in range(i+1,len(points)-1):
                    for k in range(j+1,len(points)):
                        if compute(points[i],points[j]) == compute(points[i],points[k]):
                            res += 2
                        if compute(points[i],points[j]) == compute(points[j],points[k]):
                            res += 2
                        if compute(points[k],points[j]) == compute(points[i],points[k]):
                            res += 2
            return res
    

    Brute force.
    24 / 31 test cases passed.

    Solution2:

    class Solution:
        def numberOfBoomerangs(self, points):
            """
            :type points: List[List[int]]
            :rtype: int
            """
            res = 0
            def compute(x,y):
                return (x[0]-y[0])**2 + (x[1]-y[1])**2
            for i in range(len(points)):
                dic = {}
                for j in range(len(points)):
                    if i==j:
                        continue
                    temp = compute(points[i],points[j])
                    if temp not in dic:
                        dic[temp] = 1
                    else:
                        dic[temp] += 1
                for key,value in dic.items():
                    res += value*(value-1)
            return res
    

    典型的以空间换时间的策略,用一个字典保存每个点到该点的距离,从而将时间复杂度从O(n3)降到了O(n2)。

  • 相关阅读:
    Docker 介绍
    Docker 教程
    Python 删除文件与文件夹
    Python 读文件
    Python 打开文件(File Open)
    Python 异常处理(Try...Except)
    什么是拜占庭将军问题
    智能合约语言 Solidity 教程系列7
    给代币添加高级功能-代币管理、增发、兑换、冻结等
    一步步教你创建自己的数字货币(代币)进行ICO
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/10235257.html
Copyright © 2011-2022 走看看