150 najlepszych wywiadówŁatwe

Dwie sumy II

Szczegółowy przewodnik i implementacja Python dla problemu „Two Sum II”.

Oświadczenie o problemie

Łatwe

Mając tablicę liczb całkowitych numbers o indeksie 1, która jest już posortowana w porządku niemalejącym, znajdź dwie liczby takie, że sumują się do określonej liczby target.

Zwróć indeksy dwóch liczb, index1 i index2, dodane przez jeden jako tablicę liczb całkowitych [index1, index2] o długości 2.

Nie możesz użyć tego samego elementu dwa razy. Twoje rozwiązanie musi wykorzystywać tylko stałą dodatkową przestrzeń.

Napisz funkcję twoSum(numbers: List[int], target: int) -> List[int].

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

Przykłady

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?
Rozważ użycie struktur danych specyficznych dla dwóch wskaźników, takich jak zestawy lub sterty.
Edge Cases to Watch
  • Puste struktury wejściowe
  • Wejścia jednoelementowe
  • Duże granice liczbowe

Gotowy do rozwiązania?

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

Otwórz w Edytorze
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

Polecane zasoby Pythona

Poszerzaj swoją wiedzę dzięki powiązanym interaktywnym samouczkom, ściągawkom i porównaniom kodów.