Leetcode 253: Meeting Rooms II

Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.

For example,
Given [[0, 30],[5, 10],[15, 20]],
return 2.

 

 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 public class Solution {
11     public class IntervalComparer : IComparer<Interval>
12     {
13         public int Compare(Interval a, Interval b)
14         {
15             return a.start == b.start ? a.end - b.end : a.start - b.start;
16         }
17     }
18     
19     public int MinMeetingRooms(Interval[] intervals) {       
20         if (intervals == null || intervals.Length == 0) return 0;
21         if (intervals.Length == 1) return 1;
22         
23         Array.Sort(intervals, new IntervalComparer());
24         
25         // the ideal datastructure to solve this a priority queue, however C# doesn't have impletemented it yet
26         // so I'll use a sorted list here
27         var rooms = new List<int>(intervals.Length);
28         var max = 1;
29         
30         for (int i = 0; i < intervals.Length; i++)
31         {
32             if (i == 0)
33             {
34                 rooms.Add(intervals[0].end);
35             }
36             else
37             {
38                 if (intervals[i].start >= rooms[0])
39                 {
40                     rooms.RemoveAt(0);
41                 }
42 
43                 int index = rooms.BinarySearch(intervals[i].end);
44                 rooms.Insert(index < 0 ? ~index : index, intervals[i].end);
45             }
46             
47             max = Math.Max(max, rooms.Count);
48         }
49         
50         return max;
51     }
52 }

 

posted @ 2017-12-19 03:54  逸朵  阅读(445)  评论(0)    收藏  举报