İçeriğe atla
DSA Patterns
Menü
Dil
Heap ve Top KLC #2152 / 6← ÖncekiSonraki →

Demo önizleme: Bu çözümler otomatik test paketini geçiyor ama insan tarafından incelenmedi. Trade-off ve yazıları taslak olarak değerlendirin.

Kth Largest Element in an Array

Problem (yeniden ifade)

Sıralanmamış bir dizide k. en büyük elemanı bul (benzersiz olma şartı yok).

Sezgi

Boyu k min-heap görülen en büyük k’yı tutar; kök k. en büyük. Quick select, pivot n-k indeksine oturana dek partition eder.

Yaklaşımlar

Boyu k min-heap

Doğrulanmadı
Zaman O(n log k)Alan O(k)

Fikir. Hepsini push et; size>k olunca pop; peek döndür.

Yürüyüş. [3,2,1,5,6,4], k=2 → 5.

Trade-off. Heap O(n log k) vs quickselect ortalama O(n). k çok küçükse veya dizi bozulmamalıysa heap tercih et.

Çözüm
Yardımcı kodu göster
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
  private a: T[] = [];
  private less: (x: T, y: T) => boolean;
  constructor(less: (x: T, y: T) => boolean) {
    this.less = less;
  }
  get size(): number {
    return this.a.length;
  }
  peek(): T {
    return this.a[0]!;
  }
  push(x: T): void {
    const a = this.a;
    a.push(x);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (!this.less(a[i]!, a[p]!)) break;
      [a[i], a[p]] = [a[p]!, a[i]!];
      i = p;
    }
  }
  pop(): T {
    const a = this.a;
    const top = a[0]!;
    const last = a.pop()!;
    if (a.length) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let s = i;
        if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
        if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
        if (s === i) break;
        [a[i], a[s]] = [a[s]!, a[i]!];
        i = s;
      }
    }
    return top;
  }
}
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
  private a: T[] = [];
  private less: (x: T, y: T) => boolean;
  constructor(less: (x: T, y: T) => boolean) {
    this.less = less;
  }
  get size(): number {
    return this.a.length;
  }
  peek(): T {
    return this.a[0]!;
  }
  push(x: T): void {
    const a = this.a;
    a.push(x);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (!this.less(a[i]!, a[p]!)) break;
      [a[i], a[p]] = [a[p]!, a[i]!];
      i = p;
    }
  }
  pop(): T {
    const a = this.a;
    const top = a[0]!;
    const last = a.pop()!;
    if (a.length) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let s = i;
        if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
        if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
        if (s === i) break;
        [a[i], a[s]] = [a[s]!, a[i]!];
        i = s;
      }
    }
    return top;
  }
}
export function findKthLargest(nums: number[], k: number): number {
  // Real binary min-heap of size k; its top is the kth largest.
  const heap = new Heap<number>((a, b) => a < b);
  for (const x of nums) {
    if (heap.size < k) {
      heap.push(x);
    } else if (x > heap.peek()) {
      heap.pop();
      heap.push(x);
    }
  }
  return heap.peek();
}
export function findKthLargest(nums: number[], k: number): number {
  // Real binary min-heap of size k; its top is the kth largest.
  const heap = new Heap<number>((a, b) => a < b);
  for (const x of nums) {
    if (heap.size < k) {
      heap.push(x);
    } else if (x > heap.peek()) {
      heap.pop();
      heap.push(x);
    }
  }
  return heap.peek();
}

Quick select

Doğrulanmadı
Zaman O(n) averageAlan O(1)

Fikir. k. en büyük, sıralı düzende n-k indeksindeki elemandır. Pivot oraya oturana dek rastgele partition; yalnızca bir tarafa ilerle. Diziyi yerinde değiştirir.

Yürüyüş. [3,2,1,5,6,4], k=2 → hedef indeks 4. Partition’lardan sonra 4. indeksteki değer 5.

Trade-off. Ortalama O(n), rastgele pivot yoksa en kötü O(n²). Quick Select varsayılanı. k 1-indeksli.

Çözüm
export function findKthLargest(nums: number[], k: number): number {
  const target = nums.length - k;
  let lo = 0, hi = nums.length - 1;
  while (lo <= hi) {
    const p = partition(nums, lo, hi);
    if (p === target) return nums[p]!;
    if (p < target) lo = p + 1;
    else hi = p - 1;
  }
  return nums[lo]!;
}

function partition(nums: number[], lo: number, hi: number): number {
  const rand = lo + Math.floor(Math.random() * (hi - lo + 1));
  [nums[rand], nums[hi]] = [nums[hi]!, nums[rand]!];
  const pivot = nums[hi]!;
  let i = lo;
  for (let j = lo; j < hi; j++) {
    if (nums[j]! < pivot) {
      [nums[i], nums[j]] = [nums[j]!, nums[i]!];
      i++;
    }
  }
  [nums[i], nums[hi]] = [nums[hi]!, nums[i]!];
  return i;
}
export function findKthLargest(nums: number[], k: number): number {
  const target = nums.length - k;
  let lo = 0, hi = nums.length - 1;
  while (lo <= hi) {
    const p = partition(nums, lo, hi);
    if (p === target) return nums[p]!;
    if (p < target) lo = p + 1;
    else hi = p - 1;
  }
  return nums[lo]!;
}

function partition(nums: number[], lo: number, hi: number): number {
  const rand = lo + Math.floor(Math.random() * (hi - lo + 1));
  [nums[rand], nums[hi]] = [nums[hi]!, nums[rand]!];
  const pivot = nums[hi]!;
  let i = lo;
  for (let j = lo; j < hi; j++) {
    if (nums[j]! < pivot) {
      [nums[i], nums[j]] = [nums[j]!, nums[i]!];
      i++;
    }
  }
  [nums[i], nums[hi]] = [nums[hi]!, nums[i]!];
  return i;
}

Şablon bağlantısı

Heap top-K, veya n-k sırası için Quick Select. Her iki pattern için amiral gemisi k. en büyük problemi.

Yansıma

  • k boyutlu min-heap’in tepesi k’ıncı büyük. n’i itip k’dan büyükse pop. Quickselect ortalama O(n).
  • k == n en küçük, k == 1 en büyük. Yinelenenler ayrı eleman sayılır; tekilleştirme yok.
  • Kötü pivot quickselect’i O(n²) yapar. Heap O(n log k) garanti.
Katkıda bulunan inceleme listesi

Etkileşimli

Zihinsel model

Bu problem için animasyonlu çözüm. Adımları kaydır veya boşlukla duraklat; değişmezi yüksek sesle yeniden anlat.

Adım 1 / 6
1/6

[3,2,1,5,6,4] içinde k=2. en büyük. Boyu k olan min-heap tut.

3
0
2
1
1
2
5
3
6
4
4
5

k = 2 · min-heap

Gösterim:GüncelAktif aralıkSol / yavaşEşleşmeTamamElendi