Le migliori 150 intervisteFacile

3Somma

Guida dettagliata e implementazione Python per il problema '3Sum'.

Dichiarazione del problema

Facile

Dato un array di numeri interi nums, restituisce tutte le triplette [nums[i], nums[j], nums[k]] tali che i != j, i != k e j != k e nums[i] + nums[j] + nums[k] == 0.

Si noti che il set di soluzioni non deve contenere triplette duplicate.

Scrivi una funzione threeSum(nums: List[int]) -> List[List[int]].

Vincoli
  • 3 <= len(nums) <= 3000
  • -10^5 <= nums[i] <= 10^5

Esempi

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?
Prendi in considerazione l'utilizzo di strutture dati specifiche di Two Pointers come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Apri nell'editor
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

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.