题目:
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
.
两种做法。都需要先根据start排序原数组。然后要么用最小堆,要么对每一个start,遍历end,比较end是否小于等于start。
C++的priority_queue是最大堆,Java的PriorityQueue和Python的heapq是最小堆。面试的时候可以需求选择适当的语言。
C++版:
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: int minMeetingRooms(vector<Interval>& intervals) { vector<int> s(intervals.size()); vector<int> e(intervals.size()); for(int i = 0; i < intervals.size(); i++) { s[i] = intervals[i].start; e[i] = intervals[i].end; } sort(s.begin(), s.end()); sort(e.begin(), e.end()); int eIndex = 0, room = 0, available = 0; for(auto i : s) { while(e[eIndex] <= i) { available++; eIndex++; } if(available > 0) available--; else room++; } return room; } };
/** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ import java.util.Arrays; public class Solution { public int minMeetingRooms(Interval[] intervals) { Arrays.sort(intervals, new IntervalComparator()); PriorityQueue<Integer> minHeap = new PriorityQueue(); int rooms = 0; for(int i = 0; i < intervals.length; i++) { if(minHeap.size() == 0) { minHeap.add(intervals[i].end); rooms++; continue; } if(minHeap.peek() <= intervals[i].start) { minHeap.poll(); minHeap.add(intervals[i].end); } else { minHeap.add(intervals[i].end); rooms++; } } return rooms; } } class IntervalComparator implements Comparator<Interval> { public int compare(Interval a, Interval b) { return a.start - b.start; } }
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e import heapq class Solution(object): def minMeetingRooms(self, intervals): """ :type intervals: List[Interval] :rtype: int """ heap, num = [], 0 heapq.heapify(heap) intervals.sort(lambda a, b : a.start - b.start) for i in range(len(intervals)): if len(heap) == 0: heapq.heappush(heap, intervals[i].end) num += 1 continue if heap[0] <= intervals[i].start: heapq.heappop(heap) heapq.heappush(heap, intervals[i].end) else: heapq.heappush(heap, intervals[i].end) num +=1 return num