150 najlepszych wywiadówŁatwe

3Suma

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

Oświadczenie o problemie

Łatwe

Mając tablicę liczb całkowitych nums, zwróć wszystkie trójki [nums[i], nums[j], nums[k]] takie, jak i != j, i != k i j != k oraz nums[i] + nums[j] + nums[k] == 0.

Należy zauważyć, że zbiór rozwiązań nie może zawierać zduplikowanych trójek.

Napisz funkcję threeSum(nums: List[int]) -> List[List[int]].

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

Przykłady

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?
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.