[路飞]_前端算法第八十二弹-最接近原点的 K 个点

119 阅读1分钟

我们有一个由平面上的点组成的列表 points。需要从中找出 K 个距离原点 (0, 0) 最近的点。

(这里,平面上两点之间的距离是欧几里德距离。)

你可以按任何顺序返回答案。除了点坐标的顺序之外,答案确保是唯一的。

示例 1:

输入:points = [[1,3],[-2,2]], K = 1
输出:[[-2,2]]
解释: 
(1, 3) 和原点之间的距离为 sqrt(10),
(-2, 2) 和原点之间的距离为 sqrt(8),
由于 sqrt(8) < sqrt(10),(-2, 2) 离原点更近。
我们只需要距离原点最近的 K = 1 个点,所以答案就是 [[-2,2]]

示例 2:

输入:points = [[3,3],[5,-1],[-2,4]], K = 2
输出:[[3,3],[-2,4]]
(答案 [[-2,4],[3,3]] 也会被接受。)

这里我们使用小顶堆,我们将数组元素和其欧几里德距离加入到小顶堆中,并取出前K个元素

var kClosest = function (points, k) {
  let heap = new Heap((a, b) => a.sqrt > b.sqrt);
  let res = []
  for (let i = 0; i < points.length; i++) {
    const sqrt = Math.pow(points[i][0], 2) + Math.pow(points[i][1], 2)
    heap.push({
      point: points[i],
      sqrt
    })
  }
  for (let i = 0; i < k; i++) {
    res.push(heap.pop().point)
  }
  return res
};

堆的一般写法

class Heap {
    constructor(cmp = "large") {
        if (cmp == "large") {
            this.cmp = this.large;
        } else if (cmp == "small") {
            this.cmp = this.small
        } else {
            this.cmp = cmp
        }
        this.res = [];
        this.cnt = 0;
    }

    push(val) {
        this.cnt++;
        this.res.push(val)
        this.shiftUp(this.cnt - 1)
    }

    pop() {
        this.cnt--;
        const res = this.res[0]
        const pop = this.res.pop()
        if (this.cnt) {
            this.res[0] = pop
            this.shiftDown(0)
        }
        return res
    }

    shiftUp(i) {
        if (i === 0) return
        const par = this.getParentIndex(i)
        if (this.cmp(this.res[par], this.res[i])) {
            this.swap(par, i)
            this.shiftUp(par)
        }
    }

    shiftDown(i) {
        const l = this.getLeftIndex(i)
        const r = this.getRightIndex(i)
        if (l < this.cnt && this.cmp(this.res[i], this.res[l])) {
            this.swap(i, l)
            this.shiftDown(l)
        }
        if (r < this.cnt && this.cmp(this.res[i], this.res[r])) {
            this.swap(i, r)
            this.shiftDown(r)
        }
    }

    getParentIndex(i) {
        return (i - 1) >> 1
    }

    getLeftIndex(i) {
        return i * 2 + 1
    }

    getRightIndex(i) {
        return i * 2 + 2
    }

    large = (a, b) => a < b

    small = (a, b) => a > b;

    swap = (i, j) => [this.res[i], this.res[j]] = [this.res[j], this.res[i]];

    top = () => this.res[0];

    size = () => this.cnt;

    isEmpty = () => this.cnt === 0

}