150強訪談

兩個排序數組的中位數

「兩個排序數組的中位數」問題的詳細指南和 Python 實作。

問題陳述

給定兩個排序數組 nums1nums2,大小分別為 mn,傳回兩個排序數組的中位數。

總體運行時間複雜度應為 O(log(m+n))。

寫一個函數 findMedianSortedArrays(nums1: List[int], nums2: List[int]) -> float

約束條件
  • nums1.length == m, nums2.length == n
  • 0 <= m <= 1000
  • 0 <= n <= 1000
  • 1 <= m + n <= 2000
  • -10^6 <= nums1[i], nums2[i] <= 10^6

範例

Example 1
Input
nums1 = [1, 3], nums2 = [2]
Output
2.0
Explanation

Merged array = [1, 2, 3]. The median is 2.0.

Example 2
Input
nums1 = [1, 2], nums2 = [3, 4]
Output
2.5
Explanation

Merged array = [1, 2, 3, 4]. The median is (2 + 3) / 2 = 2.5.

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

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