Le migliori 150 intervisteFacile

K-esimo elemento più grande nel flusso

Guida dettagliata e implementazione Python per il problema "Kth Largest Element In Stream".

Dichiarazione del problema

Facile

Progetta una classe per trovare il kesimo elemento più grande in un flusso. Si noti che è il k-esimo elemento più grande nell'ordine, non il k-esimo elemento distinto.

Implementa la classe KthLargest:

- KthLargest(k: int, nums: List[int]) Inizializza l'oggetto con l'intero k e il flusso di numeri interi.

- add(val: int) -> int Aggiunge l'intero val allo stream e restituisce l'elemento che rappresenta il kesimo elemento più grande.

L'input è un elenco di operazioni e argomenti. Implementa una funzione kthLargest(operations: list, arguments: list) -> list che restituisce un elenco di risultati (Nessuno per il costruttore, int per l'aggiunta).

Vincoli
  • 1 <= k <= 10^4
  • 0 <= len(nums) <= 10^4
  • -10^4 <= nums[i], val <= 10^4
  • At most 10^4 calls will be made to add

Esempi

Example 1
Input
operations = ["KthLargest", "add", "add", "add", "add", "add"], arguments = [[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output
[None, 4, 5, 5, 8, 8]
Explanation

KthLargest class is initialized with k=3 and nums=[4,5,8,2]. add(3) returns 4. add(5) returns 5. add(10) returns 5. add(9) returns 8. add(4) returns 8.

Need a Hint?
Prendi in considerazione l'utilizzo di strutture dati specifiche per heap/coda di priorità 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.