150強訪談簡單

流中第 K 最大元素

「流中第 K 個最大元素」問題的詳細指南和 Python 實作。

問題陳述

簡單

設計一個類別來尋找流中的第 k 大元素。請注意,它是排序順序中的第 k 個最大元素,而不是第 k 個不同元素。

實作 KthLargest 類別:

- KthLargest(k: int, nums: List[int]) 使用整數 k 和整數流 nums 初始化物件。

- add(val: int) -> int 將整數 val 追加到流中並傳回表示第 k 個最大元素的元素。

輸入是操作和參數的清單。實作一個函數 kthLargest(operations: list, arguments: list) -> list 傳回結果清單(建構函式為 None,add 為 int)。

約束條件
  • 1 <= k <= 10^4
  • 0 <= len(nums) <= 10^4
  • -10^4 <= nums[i], val <= 10^4
  • At most 10^4 calls will be made to add

範例

Example 1
Input
operations = ["KthLargest", "add", "add", "add", "add", "add"], arguments = [[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output
[None, 4, 5, 5, 8, 8]
Explanation

KthLargest class is initialized with k=3 and nums=[4,5,8,2]. add(3) returns 4. add(5) returns 5. add(10) returns 5. add(9) returns 8. add(4) returns 8.

Need a Hint?
考慮使用堆/優先權佇列特定的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。