Le migliori 150 intervisteFacile

Due Somma II

Guida dettagliata e implementazione Python per il problema 'Two Sum II'.

Dichiarazione del problema

Facile

Dato un array di numeri interi con indice 1 numbers che è già ordinato in ordine non decrescente, trova due numeri tali che la loro somma dia un numero target specifico.

Restituisce gli indici dei due numeri, index1 e index2, sommati di uno come array di numeri interi [index1, index2] di lunghezza 2.

Non puoi utilizzare lo stesso elemento due volte. La tua soluzione deve utilizzare solo spazio aggiuntivo costante.

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

Vincoli
  • 2 <= len(numbers) <= 3 * 10^4
  • -1000 <= numbers[i] <= 1000
  • numbers is sorted in non-decreasing order
  • -1000 <= target <= 1000
  • Exactly one solution exists

Esempi

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

2 + 7 = 9. The indices are 1 and 2 (1-indexed).

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

2 + 4 = 6. The indices are 1 and 3 (1-indexed).

Example 3
Input
numbers = [-1, 0], target = -1
Output
[1, 2]
Explanation

-1 + 0 = -1. The indices are 1 and 2 (1-indexed).

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.