150強訪談簡單

數組中第 K 個最大元素

“數組中的第 K 個最大元素”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個整數數組 nums 和一個整數 k,傳回數組中第 k 個最大的元素。

請注意,它是排序順序中的第 k 個最大元素,而不是第 k 個不同元素。

你能以 O(n) 的複雜度解決這個問題嗎?

寫一個函數 findKthLargest(nums: List[int], k: int) -> int

約束條件
  • 1 <= k <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4

範例

Example 1
Input
nums = [3,2,1,5,6,4], k = 2
Output
5
Explanation

The sorted array is [1,2,3,4,5,6]. The 2nd largest element is 5.

Example 2
Input
nums = [3,2,3,1,2,4,5,5,6], k = 4
Output
4
Explanation

The sorted array is [1,2,2,3,3,4,5,5,6]. The 4th largest element is 4.

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 資源

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