1 /**2 * Definition for an interval.3 * public class Interval {4 * public int start;5 * public int end;6 * public Interval() { start = 0; end = 0; }7 * public Interval(int s, int e) { start = s; end = e; }8 * }9 */
10
11 public classMinHeap12 {13 private Listitems;14
15 publicMinHeap()16 {17 this.items = new List();18 }19
20 public void Push(intitem)21 {22 int i = this.items.Count;23 this.items.Add(item);24
25 while (i > 0 && this.items[(i - 1) / 2] >item)26 {27 this.items[i] = this.items[(i - 1) / 2];28 i = (i - 1) / 2;29 }30
31 this.items[i] =item;32 }33
34 public intPop()35 {36 if (this.items.Count == 0)37 {38 throw newException();39 }40
41 int ret = this.items[0];42 int last = this.items[this.items.Count - 1];43
44 this.items.RemoveAt(this.items.Count - 1);45
46 if (items.Count > 0)47 {48 int i = 0;49
50 while (i < items.Count / 2)51 {52 int j = 2 * i + 1;53
54 if (j < items.Count - 1 && items[j + 1]
59 if (last <= this.items[j])60 {61 break;62 }63
64 items[i] =items[j];65 i =j;66 }67
68 items[i] =last;69 }70
71 returnret;72
73 }74
75 public intPeek()76 {77 return this.items[0];78 }79
80 public intCount81 {82 get { return this.items.Count; }83 }84 }85
86
87 public classSolution1 {88 public class IntervalComparer : IComparer
89 {90 public intCompare(Interval a, Interval b)91 {92 return a.start == b.start ? a.end - b.end : a.start -b.start;93 }94 }95
96 //idea: 1. sort the meetings by start time97 //2. put the end time into a min heap, if the current meeting‘s start time is greater or equal than the peek item98 //in the min heap, we can pop out the peek and push the current meeting‘s end time in, otherwise we just push99 //the current meeting‘s end time into the heap
100 public intMinMeetingRooms(Interval[] intervals) {101 if (intervals == null || intervals.Length == 0) return 0;102 if (intervals.Length < 2) returnintervals.Length;103
104 Array.Sort(intervals, newIntervalComparer());105
106 MinHeap minHeap = newMinHeap();107
108 foreach (var interval inintervals)109 {110 if (minHeap.Count == 0)111 {112 minHeap.Push(interval.end);113 }114 else
115 {116 if (interval.start >=minHeap.Peek())117 {118 minHeap.Pop();119 }120
121 minHeap.Push(interval.end);122 }123 }124
125 returnminHeap.Count;126 }127 }128
129 public classSolution {130 //idea: seehttps://discuss.leetcode.com/topic/35253/explanation-of-super-easy-java-solution-beats-98-8-from-pinkfloyda/2
131 public intMinMeetingRooms(Interval[] intervals) {132 if (intervals == null || intervals.Length == 0) return 0;133 if (intervals.Length < 2) returnintervals.Length;134
135 var starts = new int[intervals.Length];136 var ends = new int[intervals.Length];137
138 for (int i = 0; i < intervals.Length; i++)139 {140 starts[i] =intervals[i].start;141 ends[i] =intervals[i].end;142 }143
144 Array.Sort(starts);145 Array.Sort(ends);146
147 int rooms = 0, j = 0;148
149 for (int i = 0; i < intervals.Length; i++)150 {151 if (starts[i]
156 {157 j++;158 }159 }160
161 returnrooms;162 }163 }