Python 基礎知識簡單

尋找數組中的所有對稱對

「尋找數組中的所有對稱對」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 symmetric_pairs(arr) ,它接受對列表(2 元素列表的列表)並傳回所有對稱對。如果數組中存在一對 [a, b] ,則它們與另一對 [b, a] 對稱。傳回結果作為對的排序列表,其中對的第一個元素較小。每個對稱對應該只出現一次。

約束條件
  • 1 <= len(arr) <= 10^4
  • Each element is a list of 2 integers
  • -10^6 <= arr[i][j] <= 10^6

範例

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

[1,2] and [2,1] are symmetric. [3,4] and [4,3] are symmetric. [5,6] has no symmetric pair.

Example 2
Input
arr = [[1, 2], [3, 4]]
Output
[]
Explanation

No pair has its reverse in the array.

Example 3
Input
arr = [[10, 20], [20, 10]]
Output
[[10, 20]]
Explanation

[10,20] and [20,10] form a symmetric pair.

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

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