标签:
题目:
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
.
链接: http://leetcode.com/problems/meeting-rooms-ii/
题解:
给定一个interval数组,求最少需要多少间教室。初始想法是扫描线算法sweeping-line algorithm,先把数组排序,之后维护一个min-oriented heap。遍历排序后的数组,每次把interval[i].end加入到heap中,然后比较interval.start与pq.peek(),假如interval[i].start >= pq.peek(),说明pq.peek()所代表的这个meeting已经结束,我们可以从heap中把这个meeting的end time移除,继续比较下一个pq.peek()。比较完毕之后我们尝试更新maxOverlappingMeetings。 像扫描线算法和heap还需要好好复习, 直线,矩阵的相交也可以用扫描线算法。
Time Complexity - O(nlogn), Space Complexity - O(n)
/** * 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; } * } */ public class Solution { public int minMeetingRooms(Interval[] intervals) { if(intervals == null || intervals.length == 0) return 0; Arrays.sort(intervals, new Comparator<Interval>() { public int compare(Interval t1, Interval t2) { if(t1.start != t2.start) return t1.start - t2.start; else return t1.end - t2.end; } }); int maxOverlappingMeetings = 0; PriorityQueue<Integer> pq = new PriorityQueue<>(); // min oriented priority queue for(int i = 0; i < intervals.length; i++) { // sweeping-line algorithms pq.add(intervals[i].end); while(pq.size() > 0 && intervals[i].start >= pq.peek()) pq.remove(); maxOverlappingMeetings = Math.max(maxOverlappingMeetings, pq.size()); } return maxOverlappingMeetings; } }
Reference:
标签:
原文地址:http://www.cnblogs.com/yrbbest/p/5012534.html