150 najlepszych wywiadówŁatwe

Dwie sumy

Szczegółowy przewodnik i implementacja Python dla problemu „Dwie sumy”.

Oświadczenie o problemie

Łatwe

Mając tablicę liczb całkowitych nums i liczbę całkowitą target, zwróć indeksy obu liczb w taki sposób, aby ich suma wynosiła target.

Możesz założyć, że każde wejście będzie miało dokładnie jedno rozwiązanie i nie możesz użyć tego samego elementu dwa razy.

Odpowiedź możesz zwrócić w dowolnej kolejności.

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

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

Przykłady

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?
Rozważ użycie struktur danych specyficznych dla tablic i haszowania, 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.