Le migliori 150 intervisteFacile

Due somme

Guida dettagliata e implementazione Python per il problema "Due somme".

Dichiarazione del problema

Facile

Dato un array di numeri interi nums e un numero intero target, restituisci gli indici dei due numeri in modo che la loro somma dia target.

Puoi presumere che ogni input abbia esattamente una soluzione e non puoi utilizzare lo stesso elemento due volte.

Puoi restituire la risposta in qualsiasi ordine.

Scrivi una funzione twoSum(nums: List[int], target: int) -> List[int].

Vincoli
  • 2 <= len(nums) <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • Only one valid answer exists

Esempi

Example 1
Input
nums = [2, 7, 11, 15], target = 9
Output
[0, 1]
Explanation

nums[0] + nums[1] = 2 + 7 = 9, so we return [0, 1].

Example 2
Input
nums = [3, 2, 4], target = 6
Output
[1, 2]
Explanation

nums[1] + nums[2] = 2 + 4 = 6, so we return [1, 2].

Example 3
Input
nums = [3, 3], target = 6
Output
[0, 1]
Explanation

nums[0] + nums[1] = 3 + 3 = 6, so we return [0, 1].

Need a Hint?
Prendi in considerazione l'utilizzo di strutture dati specifiche per array e hashing 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.