Le migliori 150 intervisteFacile

Elementi frequenti in alto K

Guida dettagliata e implementazione Python per il problema 'Top K Frequent Elements'.

Dichiarazione del problema

Facile

Dato un array di numeri interi nums e un numero intero k, restituisce gli elementi k più frequenti. Puoi restituire la risposta in qualsiasi ordine.

Scrivi una funzione topKFrequent(nums: List[int], k: int) -> List[int].

Vincoli
  • 1 <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • k is in the range [1, number of unique elements in nums]
  • The answer is guaranteed to be unique

Esempi

Example 1
Input
nums = [1, 1, 1, 2, 2, 3], k = 2
Output
[1, 2]
Explanation

1 appears 3 times and 2 appears 2 times. These are the 2 most frequent elements.

Example 2
Input
nums = [1], k = 1
Output
[1]
Explanation

There is only one element, so it is the most frequent.

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.