150強訪談簡單

3總和

“3Sum”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個整數陣列 nums,傳回所有三元組 [nums[i], nums[j], nums[k]],這樣 i != ji != kj != knums[i] + nums[j] + nums[k] == 0

請注意,解決方案集不得包含重複的三元組。

寫一個函數 threeSum(nums: List[int]) -> List[List[int]]

約束條件
  • 3 <= len(nums) <= 3000
  • -10^5 <= nums[i] <= 10^5

範例

Example 1
Input
nums = [-1, 0, 1, 2, -1, -4]
Output
[[-1, -1, 2], [-1, 0, 1]]
Explanation

nums[0] + nums[1] + nums[2] = -1 + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = -1 + 2 + (-1) = 0. The distinct triplets are [-1,-1,2] and [-1,0,1].

Example 2
Input
nums = [0, 1, 1]
Output
[]
Explanation

No triplet sums to 0.

Example 3
Input
nums = [0, 0, 0]
Output
[[0, 0, 0]]
Explanation

The only possible triplet sums to 0.

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

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