150 najlepszych wywiadówŁatwe

Najdłuższa sekwencja sekwencyjna

Szczegółowy przewodnik i implementacja Python dla problemu „Najdłuższa sekwencja sekwencyjna”.

Oświadczenie o problemie

Łatwe

Biorąc pod uwagę nieposortowaną tablicę liczb całkowitych nums, zwróć długość najdłuższego ciągu kolejnych elementów.

Musisz napisać algorytm działający w czasie O(n).

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

Ograniczenia
  • 0 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9

Przykłady

Example 1
Input
nums = [100, 4, 200, 1, 3, 2]
Output
4
Explanation

The longest consecutive elements sequence is [1, 2, 3, 4]. Its length is 4.

Example 2
Input
nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
Output
9
Explanation

The longest consecutive elements sequence is [0, 1, 2, 3, 4, 5, 6, 7, 8]. Its length is 9.

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.