leetcode 算法题447 (简单113) 回旋镖的数量
- 题目介绍
给定平面上 n 对不同的点,“回旋镖” 是由点表示的元组 (i, j, k) ,
其中 i 和 j 之间的距离和 i 和 k 之间的距离相等(需要考虑元组的顺序)。
找到所有回旋镖的数量。
你可以假设 n 最大为 500,所有点的坐标在闭区间 [-10000, 10000] 中。
- 示例
输入: [[0,0],[1,0],[2,0]]
输出: 2
解释: 两个回旋镖为 [[1,0],[0,0],[2,0]] 和 [[1,0],[2,0],[0,0]]
- 解法一
/**
* @param {number[][]} points
* @return {number}
*/
var numberOfBoomerangs = function(points) {
if(points.length < 3) {
return 0;
}
let x = 0, y = 1, z = 2, count = 0;
while(x < points.length - 2) {
y = x + 1;
while(y < points.length - 1) {
z = y + 1;
while(z < points.length) {
count += getBoomerangsNumber(points[x], points[y], points[z++]);
}
y++;
}
x++;
}
return count;
};
const getBoomerangsNumber = (i, j, k) => {
let x = (i[0] - j[0]) * (i[0] - j[0]) + (i[1] - j[1]) * (i[1] - j[1]);
let y = (i[0] - k[0]) * (i[0] - k[0]) + (i[1] - k[1]) * (i[1] - k[1]);
let z = (j[0] - k[0]) * (j[0] - k[0]) + (j[1] - k[1]) * (j[1] - k[1]);
if(x === y) {
if(y === z) {
return 6;
}
return 2;
}
if(y === z || x === z) {
return 2;
}
return 0;
}
执行用时 : 1412 ms, 在所有 JavaScript 提交中击败了18.87%的用户
内存消耗 : 35.2 MB, 在所有 JavaScript 提交中击败了87.50%的用户
- 解法二
/**
* @param {number[][]} points
* @return {number}
*/
var numberOfBoomerangs = function(points) {
if(points.length < 3) {
return 0;
}
let x = 0, y = 1, z = 2, count = 0, dSquares = Array(points.length).fill();
while(x < points.length) {
if(!dSquares[x]) {
dSquares[x] = [];
}
dSquares[x][x] = 0;
y = x + 1;
while(y < points.length) {
let distanceSquare = getDistanceSquare(points[x], points[y]);
dSquares[x][y] = distanceSquare;
if(!dSquares[y]) {
dSquares[y] = [];
}
dSquares[y][x] = distanceSquare;
y++;
}
x++;
}
console.log(dSquares)
x = 0;
while(x < points.length - 2) {
y = x + 1;
while(y < points.length - 1) {
z = y + 1;
while(z < points.length) {
count += getBoomerangsNumber(dSquares[x][y], dSquares[y][z], dSquares[z++][x]);
}
y++;
}
x++;
}
return count;
};
const getDistanceSquare = (x, y) => {
return (x[0] - y[0]) * (x[0] - y[0]) + (x[1] - y[1]) * (x[1] - y[1]);
}
const getBoomerangsNumber = (x, y, z) => {
if(x === y) {
if(y === z) {
return 6;
}
return 2;
}
if(y === z || x === z || y === z) {
return 2;
}
return 0;
}
执行用时 : 756 ms, 在所有 JavaScript 提交中击败了48.00%的用户
内存消耗 : 56.4 MB, 在所有 JavaScript 提交中击败了50.00%的用户
- 解法三
/**
* @param {number[][]} points
* @return {number}
*/
var numberOfBoomerangs = function(points) {
if (points.length < 3) {
return 0;
}
let x = 0, y = 0, dMap = {}, count = 0;
while (x < points.length) {
y = 0;
dMap = {};
while (y < points.length) {
let distanceSquare = getDistanceSquare(points[x], points[y++]);
if (dMap[distanceSquare]) {
dMap[distanceSquare]++;
} else {
dMap[distanceSquare] = 1;
}
}
for (let key in dMap) {
count += (dMap[key] * (dMap[key] - 1))
}
x++;
}
return count;
};
const getDistanceSquare = (x, y) => {
return (x[0] - y[0]) * (x[0] - y[0]) + (x[1] - y[1]) * (x[1] - y[1]);
}
执行用时 : 1232 ms, 在所有 JavaScript 提交中击败了26.00%的用户
内存消耗 : 61.8 MB, 在所有 JavaScript 提交中击败了18.75%的用户