[LeetCode By Go 52]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]]

解题思路

代码

NumberOfBoomerangs.go

package _447_Number_Boomerangs

import "fmt"

func NumberOfBoomerangs(points [][]int) int {
    var num int
    len1 := len(points)
    for i := 0; i < len1; i++ {
        var distanceMap map[int]int
        distanceMap = make(map[int]int)
        for j := 0; j < len1; j++ {
            if i == j {
                continue
            }
            a := points[i][0] - points[j][0]
            b := points[i][1] - points[j][1]
            distance := a * a + b * b
            distanceMap[distance]++
        }

        fmt.Printf("i:%+v, map:%+v\n", i, distanceMap)
        for _, v := range distanceMap {
            num += v * (v - 1)
        }
    }

    return num
}

测试

NumberOfBoomerangs_test.go

package _447_Number_Boomerangs

import "testing"

func TestNumberOfBoomerangs(t *testing.T) {
    var tests = []struct{
        intput [][]int
        output int
    } {
        {
            [][]int{{0,0},{1,0},{2,0}}, 2,
        },
        {
            [][]int{{0,0}, {1,0}, {-1,0}, {0,1}, {0,-1}}, 20,
        },
    }

    for _, test := range tests {
        ret := NumberOfBoomerangs(test.intput)

        if ret == test.output {
            t.Logf("pass")
        } else {
            t.Errorf("fail, want %+v, get %+v", test.output, ret)
        }
    }
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/94b754ec5dc8
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞