Le migliori 150 intervisteFacile

Sequenza consecutiva più lunga

Guida dettagliata e implementazione Python per il problema della "sequenza consecutiva più lunga".

Dichiarazione del problema

Facile

Dato un array non ordinato di numeri interi nums, restituisce la lunghezza della sequenza di elementi consecutivi più lunga.

È necessario scrivere un algoritmo che venga eseguito in tempo O(n).

Scrivi una funzione longestConsecutive(nums: List[int]) -> int.

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

Esempi

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?
Prendi in considerazione l'utilizzo di strutture dati specifiche per array e hashing 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.