Le migliori 150 intervisteFacile

K-esimo elemento più grande nell'array

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

Dichiarazione del problema

Facile

Dato un array intero nums e un intero k, restituisce il kesimo elemento più grande nell'array.

Si noti che è il k-esimo elemento più grande nell'ordine, non il k-esimo elemento distinto.

Riesci a risolverlo con complessità O(n)?

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

Vincoli
  • 1 <= k <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4

Esempi

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

The sorted array is [1,2,3,4,5,6]. The 2nd largest element is 5.

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

The sorted array is [1,2,2,3,3,4,5,5,6]. The 4th largest element is 4.

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.