LeetCode 447. 回旋镖的数量

319 阅读1分钟

题目

给定平面上 n 对 互不相同 的点 points ,其中 points[i] = [xi, yi] 。回旋镖 是由点 (i, j, k) 表示的元组 ,其中 i 和 j 之间的距离和 i 和 k 之间的距离相等(需要考虑元组的顺序)。返回平面上所有回旋镖的数量。`

示例

 输入:points = [[0,0],[1,0],[2,0]] 
 输出:2
 解释:两个回旋镖为 [[1,0],[0,0],[2,0]][[1,0],[2,0],[0,0]]

解题思路

1.首先要清楚计算两点之间直线距离的公式,假设position1(x1,y1),position2(x2,y2),那么该两点之间的直线距离为sqrt{(x1 - x2)^{2} + (y1 - y2) ^{2}};
2.坐标位置顺序的改变会导致回旋镖数量的改变,假设距离坐标(x,y)为2的坐标点有n个,那么选择第二个坐标时就有n种选择,选择第三个坐标时有n-1种选择,所以固定点为(x,y)且距离为2的所有可能就有n*(n-1)种。

代码

 /**
 * @param {number[][]} points
 * @return {number}
 */
var numberOfBoomerangs = function (points) {
    const maps = Array(points.length)
        .fill(0)
        .map(() => ({}));
    let count = 0;
    points.forEach((a, i) => {
        const map = maps[i];
        points.forEach((b, j) => {
            if (a !== b) {
                const dist = distanceFuc(a, b);
                map[dist] = (map[dist] || 0) + 1;
            }
        });
        for (const dist in map) {
            const num = map[dist];
            if (num > 1) count += num * (num - 1);
        }
    });
    return count;
};

function distanceFuc([x1, y1], [x2, y2]) {
    return (x1 - x2) *(x1 - x2) + (y1 - y2) *(y1 - y2);
}

复杂度

时间复杂度:O(n²*max(count));
空间复杂度:O(n)

题目来源:力扣(LeetCode)

链接:leetcode-cn.com/problems/nu…

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。