競賽程式設計簡單

最近的一對

「最近對」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 closest_pair(arr) ,它接受未排序的整數數組 arr ,並從該數組傳回具有最小絕對差值的兩個整數 (x, y) 的元組。傳回的元組必須按 x <= y 進行排序。如果有多對具有相同的最小差異,則傳回具有較小 x 值的一對(如果它們相同,則傳回較小的 y 值)。

約束條件
  • 2 <= len(arr) <= 10^5
  • -10^9 <= arr[i] <= 10^9

範例

Example 1
Input
closest_pair([4, 9, 1, 32, 13])
Output
(1, 4)
Explanation

The difference between 1 and 4 is 3, which is the minimum difference possible between any two elements in the array.

Example 2
Input
closest_pair([12, 15, 17, 20, 25])
Output
(15, 17)
Explanation

The difference between 15 and 17 is 2, which is the minimum difference possible.

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

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