Torna alle sfide
Media 0 risolte 0% di accettazione

K-th Smallest Element

Find the k-th smallest value without fully sorting.

Cosa imparerai

  • Partizionare i valori attorno a un pivot
  • Ricorrere solo su un lato
  • Trovare il k-esimo più piccolo in tempo lineare medio

Problema

Return the k-th smallest value of the list (k counts from 1). Quickselect finds it in average O(n) time without sorting everything.

Implement kth_smallest(numbers, k).

Input

numbers: The list of integers. k: Which smallest value to return, starting at 1.

Output

Return the k-th smallest value.

Vincoli

1 ≤ k ≤ length ≤ 200,000

Esempi

Esempio 1
Input:
k = 3
numbers = [7, 10, 4, 3, 20, 15]

Output atteso:
expected = 7
Input:
long long k = 3;
std::vector<long long> numbers = {7, 10, 4, 3, 20, 15};

Output atteso:
long long expected = 7;
Input:
long k = 3;
long[] numbers = new long[] {7, 10, 4, 3, 20, 15};

Output atteso:
long expected = 7;

Spiegazione

Sorted: 3, 4, 7, 10, 15, 20; the 3rd smallest is 7.

Esempio 2
Input:
k = 2
numbers = [5, 5, 1]

Output atteso:
expected = 5
Input:
long long k = 2;
std::vector<long long> numbers = {5, 5, 1};

Output atteso:
long long expected = 5;
Input:
long k = 2;
long[] numbers = new long[] {5, 5, 1};

Output atteso:
long expected = 5;

Spiegazione

Sorted: 1, 5, 5; the 2nd smallest is 5 (duplicates count).

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

Ti serve solo l'elemento che si troverebbe in posizione k dopo l'ordinamento, non l'elenco completamente ordinato.

Suggerimento 2

Partiziona intorno a un pivot e ricorri o itera solo sul lato che può ancora contenere il rango target.

Suggerimento 3

Ricorda che k è basato su 1 e che i duplicati contano comunque come posizioni separate.

Complessità attesa

O(n) average time, O(1) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.