↓快轉到主要內容
  1. LeetCode/

LeetCode 973: K Closest Points to Origin

·1 分鐘· ·
LeetCode Medium Array Math Divide-and-Conquer Geometry
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2022-10-29

  • 提交紀錄:Runtime Error → Accepted

解題思路
#

要最近的 k 個,就維持一個大小為 k、堆頂是「目前最遠」的 heap(Heap 模板一)。Python 只有 min-heap,所以存 -(x² + y²)。heap 滿了之後 heappushpop,比堆頂更遠的點會馬上被彈出。距離比較用平方就好,不用開根號。

我的嘗試
#

第一版用了舊版題目的參數名稱 K(NameError),改成 k 就 AC 了。

正確解法
#

class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        heap = []
        for x, y in points:
            item = (-(x * x + y * y), x, y)
            if len(heap) < k:
                heapq.heappush(heap, item)
            else:
                heapq.heappushpop(heap, item)
        return [[x, y] for _, x, y in heap]

複雜度
#

時間 O(n log k),空間 O(k)。

要特別避免的錯誤
#

  • 要保留最近的,所以 heap 的堆頂要是最遠的:存負的距離。
  • 比較平方距離就好。

面試口說整理
#

我維持一個大小為 k 的 heap,存負的平方距離,所以堆頂是目前最遠的點;滿了之後每個新點都 pushpop,最後留下的就是最近的 k 個。時間 O(n log k)。

相關文章

LeetCode 105: Construct Binary Tree from Preorder and Inorder Traversal
·1 分鐘
LeetCode Medium Array Hash-Table Divide-and-Conquer Tree
LeetCode 105 解題筆記:前序的第一個是根,在中序裡找到根的位置就知道左子樹有幾個節點;用字典查位置,O(n)
LeetCode 215: Kth Largest Element in an Array
·1 分鐘
LeetCode Medium Array Divide-and-Conquer Sorting Heap-Priority-Queue
LeetCode 215 解題筆記:維持大小為 k 的 min-heap,堆頂就是第 k 大;或用 quickselect 平均 O(n)
LeetCode 347: Top K Frequent Elements
·1 分鐘
LeetCode Medium Array Hash-Table Divide-and-Conquer Sorting
LeetCode 347 解題筆記:先計數,再用大小為 k 的 heap 或 bucket sort(次數當 index)取出次數最多的 k 個
LeetCode 1030: Matrix Cells in Distance Order
·1 分鐘
LeetCode Easy Array Math Geometry Sorting
LeetCode 1030 解題筆記:列出所有座標,按到中心的曼哈頓距離排序;回傳的是座標,不是距離
LeetCode 892: Surface Area of 3D Shapes
·1 分鐘
LeetCode Easy Array Math Geometry Matrix
LeetCode 892 解題筆記:每疊 v 個方塊有 4v + 2 個面,再扣掉跟上方和左方相鄰的疊重疊的 2 × min 面
LeetCode 883: Projection Area of 3D Shapes
·1 分鐘
LeetCode Easy Array Math Geometry Matrix
LeetCode 883 解題筆記:俯視是非 0 的格子數,正視和側視分別是每一列、每一欄的最大值總和