[路飞]最接近原点的 K 个点

457 阅读1分钟

记录 1 道算法题

最接近原点的 K 个点

leetcode-cn.com/problems/k-…


点满足坐标系, x平方 + y平方 = 与远点距离的平方

所以计算点与原点的距离使用 Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))

但是距离的平方也是递增的,所以不开方也可以 Math.pow(x, 2) + Math.pow(y, 2)

然后为了不重复计算,我们把计算过的距离存到对象里面,用一个对象保存距离和点的坐标。

第 K 个的问题,用堆来解决,要最接近原点的 K 个点, 所以要距离小,那就用大顶堆,堆顶放整个堆里面最大的值。

堆的详细解释可以看这篇文章

    function kClosest(points, k) {
        const heap = new Heap((a, b) => {
          return b.distance - a.distance
        })

        for (let i = 0; i < points.length; i++) {
          const item = points[i]
          const distance = Math.pow(item[0], 2) + Math.pow(item[1], 2)
          // 排除掉比堆顶还大的点
          if (heap.size() > k && distance > heap.data[0].distance) continue
          heap.push({ distance, data: item })

          if (heap.size() > k) {
            heap.pop()
          }
        }

        return heap.data.reduce((a, b) => {
          a.push(b.data)
          return a
        }, [])
    }

结束