1. Question
You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. 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).
Return the number of boomerangs.
2. Analysis
Input: points = [[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]].
2.0 Whole Idea
Set a finding Map to store the distance of every other points.
const distanceRecord = {
[distance]: count
1: 2,
4: 3,
2: 1
}
2.1 Get the distance from other points to the points[i].
type Point = [number, number]
function getDistance(x: Point, y: Point): number {
return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2)
}
Notice: Don't need to square up here.
2.2 Update the distanceRecord, key
is distance, value
is the count.
distanceRecord = {
1: 2, // Means There are two points of the 1 distance from points[i]
4: 3,
2: 1
}
2.3 For loop the distanceRecord, answer += value * (value - 1)
Object.keys(distanceRecord).forEach(distance => {
answer += distanceRecord[distance] * (distanceRecord[distance] - 1)
})
Why is it value * (value - 1)
?
It's the content of Combinations and permutations.
The number of permutations of value objects taken r at a time is determined by the following formula:P(n, r) = n! / (n - r)!
5! = 5 * 4 * 3 * 2 * 1
(5 - 2)! = 3 * 2 * 1
So P(5, 2) = 5 * 4
2.4 Repeat the above 3 steps, to get the points[j], points[k]
Object.keys(distanceRecord).forEach(distance => {
answer += distanceRecord[distance] * (distanceRecord[distance] - 1)
})
3. Source code
function numberOfBoomerangs(points: number[][]): number {
type Point = [number, number]
function getDistance(x: Point, y: Point): number {
return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2)
}
type DistanceRecord = {
[prop: number]: number
}
let answer = 0;
for(let i = 0; i < points.length; i++) {
const distanceRecord: DistanceRecord = {}
for(let j = 0; j < points.length; j++) {
if(i === j) continue;
// 1.Get the distance from other points to the points[i].
const distance = getDistance(points[i] as Point, points[j] as Point);
// 2.Update the distanceRecord, `key` is distance, `value` is the count.
if(!distanceRecord[distance]) distanceRecord[distance] = 0;
distanceRecord[distance]++;
}
// 3.For loop the distanceRecord, answer += value * (value - 1)
Object.keys(distanceRecord).forEach(distance => {
answer += distanceRecord[distance] * (distanceRecord[distance] - 1)
})
}
return answer;
};
0 Comments