İçeriğe atla
ΣDSA Patterns
Menü
Dil

Aralıklar

Rehber 4 / 6 · Yol 4 / 6

Bu yazı henüz İngilizce. Arayüz Türkçe; içerik çevirisi sürüyor.

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

Mediumintervals

Meeting Rooms II

Problem (restated)

Given meeting time intervals, find the minimum number of conference rooms required.

Intuition

Sort starts and ends; sweep: start increments rooms, end frees; track peak.

Approaches

Sweep line

Tested only
Time O(n log n)Space O(n)

Idea. Two pointers on sorted starts/ends.

Walkthrough. [[0,30],[5,10],[15,20]] → 2 rooms.

Trade-offs. Sweep vs min-heap of end times.

Solution
export function minMeetingRooms(intervals: number[][]): number {
  const starts = intervals.map((x) => x[0]!).sort((a, b) => a - b);
  const ends = intervals.map((x) => x[1]!).sort((a, b) => a - b);
  let i = 0, j = 0, cur = 0, peak = 0;
  while (i < starts.length) {
    if (starts[i]! < ends[j]!) {
      cur++;
      peak = Math.max(peak, cur);
      i++;
    } else {
      cur--;
      j++;
    }
  }
  return peak;
}
export function minMeetingRooms(intervals: number[][]): number {
  const starts = intervals.map((x) => x[0]!).sort((a, b) => a - b);
  const ends = intervals.map((x) => x[1]!).sort((a, b) => a - b);
  let i = 0, j = 0, cur = 0, peak = 0;
  while (i < starts.length) {
    if (starts[i]! < ends[j]!) {
      cur++;
      peak = Math.max(peak, cur);
      i++;
    } else {
      cur--;
      j++;
    }
  }
  return peak;
}

Template connection

Intervals sweep / rooms.

Reflection