0
点赞
收藏
分享

微信扫一扫

447. Number of Boomerangs

玉字璧 2022-08-03 阅读 5


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

遍历每个point,然后找和它等距离的其他point,按距离来保存,比如有一个点a,和它距离都是1的点有b,c,d,那么一共的组合就有6种,包括:[a, b, c], [a, c, b], [a, b, d], [a, d, b], [a, c, d], [a, d, c]。这么算是不考重复的情况下。还有可能b, c坐标完全相同,那么b和c会被当成两个点算两次。

public class Solution {
public int numberOfBoomerangs(int[][] points) {
int result = 0;

for(int i = 0; i < points.length; i++) {
Map<Integer, Integer> map = new HashMap();
for(int j = 0; j < points.length; j++) {
if(i == j) continue;
int dx = points[j][0] - points[i][0], dy = points[j][1] - points[i][1];
int distance = dx * dx + dy * dy;

map.put(distance, map.getOrDefault(distance, 0) + 1);
}

for(int k : map.keySet()) {
int n = map.get(k);
result += n * (n - 1);
}
}
return result;
}
}

/**
* @param {number[][]} points
* @return {number}
*/
var numberOfBoomerangs = function(points) {
const len = points.length
if (len < 3) {
return 0
}
let count = 0
for (let i = 0; i < len; i++) {
const point1 = points[i]
// 用一个map存储其它点距离当前点point1有多少种距离可能
const map = new Map()
for (let j = 0; j < len; j++) {
if (i != j) {
const point2 = points[j]
const distance = getDistance(point1, point2)
if (!map.has(distance)) {
map.set(distance, 1)
} else {
map.set(distance, map.get(distance) + 1)
}
}
}
map.forEach(value => {
if (value > 1) {
const num = getArrangementNum(value)
count += num
}
})
}
return count
};

// 计算两点之间距离,这里其实没必要开根号
function getDistance (p1, p2) {
const distance = Math.sqrt(Math.pow(p1[0] - p2[0], 2) + Math.pow(p1[1] - p2[1], 2))
return distance
}

// 计算排列数
function getArrangementNum (n) {
return n * (n - 1)
}


举报

相关推荐

0 条评论