競賽程式設計簡單

两个数组中最接近的对

「兩個陣列中最接近的對」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 closest_pair_two_arrays(arr1, arr2, x),它接受兩個整數排序數組 arr1arr2 以及一個目標整數 x。它應該找到並傳回一個元組 (a, b) ,其中 a 來自 arr1b 來自 arr2 ,這樣 (a + b)x 之間的絕對差異最小化。如果存在多個這樣的對,則傳回 arr1 中元素最小的對。

約束條件
  • 1 <= len(arr1), len(arr2) <= 10^5
  • arr1 and arr2 are sorted in ascending order.
  • -10^9 <= arr1[i], arr2[j], x <= 10^9

範例

Example 1
Input
closest_pair_two_arrays([1, 4, 5, 7], [10, 20, 30, 40], 32)
Output
(1, 30)
Explanation

1 from arr1 and 30 from arr2 sum to 31, which is closest to 32 (absolute difference is 1).

Example 2
Input
closest_pair_two_arrays([1, 4, 5, 7], [10, 20, 30, 40], 50)
Output
(7, 40)
Explanation

7 from arr1 and 40 from arr2 sum to 47, which is closest to 50 (absolute difference is 3).

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

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