[LeetCode]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]]

難度

Easy

方法

對(duì)于每個(gè)point,用一個(gè)map統(tǒng)計(jì)各個(gè)距離d下對(duì)應(yīng)的其他point的個(gè)數(shù)n,即mapkey為距離dvalue為距離該pointd的其他point的個(gè)數(shù)n。然后An2,即n*(n-1)。最后將各個(gè)point對(duì)應(yīng)的n*(n-1)累加即可

python代碼

class Solution(object):
    def numberOfBoomerangs(self, points):
        """
        :type points: List[List[int]]
        :rtype: int
        """
        result = 0
        for point_i in points:
            distance_map = {}
            for point_j in points:
                distance = (point_i[0] - point_j[0]) * (point_i[0] - point_j[0]) + \
                           (point_i[1] - point_j[1]) * (point_i[1] - point_j[1])
                distance_map[distance] = distance_map.get(distance, 0) + 1

            for distance in distance_map:
                count = distance_map[distance]
                result += count * (count - 1)

        return result

assert Solution().numberOfBoomerangs([[0,0], [1,0], [2,0]]) == 2
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,878評(píng)論 0 23
  • 這里的夜很靜, 塵埃落在地上, 激蕩出渾厚的聲響, 一個(gè)人, 無(wú)助的蜷縮在空落落的床上, 心的方向迷失了軌跡, 用...
    灰色朦朧閱讀 214評(píng)論 0 0
  • 昨天介紹了ArrayAdapter的使用,今天介紹一下更加實(shí)用的一點(diǎn),對(duì)它進(jìn)行重寫,滿足自己的個(gè)性化設(shè)計(jì)需要. A...
    danielss閱讀 809評(píng)論 0 0