LeetCode 253. Meeting Rooms II(会议室)
Posted jmspan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 253. Meeting Rooms II(会议室)相关的知识,希望对你有一定的参考价值。
原题网址:https://leetcode.com/problems/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
.
/**
* 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)
Arrays.sort(intervals, new Comparator<Interval>()
@Override
public int compare(Interval i1, Interval i2)
return Integer.compare(i1.start, i2.start);
);
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
int rooms = 0;
for(int i=0; i<intervals.length; i++)
minHeap.offer(intervals[i].end);
if (intervals[i].start < minHeap.peek())
rooms ++;
else
minHeap.poll();
return rooms;
更直观的实现方法:
/**
* 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)
Arrays.sort(intervals, new Comparator<Interval>()
@Override
public int compare(Interval i1, Interval i2)
return Integer.compare(i1.start, i2.start);
);
int rooms = 0;
int active = 0;
PriorityQueue<Integer> heap = new PriorityQueue<>();
for(int i=0; i<intervals.length; i++)
while (!heap.isEmpty() && heap.peek() <= intervals[i].start)
active --;
heap.poll();
active ++;
heap.offer(intervals[i].end);
rooms = Math.max(rooms, active);
return rooms;
方法二:分别对起始时间和结束时间排序,由于会议之间并无差异(不像skyline问题,不同建筑的高度不一样),所以分别使用两个指针来推进起始时间和结束时间。
/**
* 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)
int[] starts = new int[intervals.length];
int[] ends = new int[intervals.length];
for(int i=0; i<intervals.length; i++)
starts[i] = intervals[i].start;
ends[i] = intervals[i].end;
Arrays.sort(starts);
Arrays.sort(ends);
int rooms = 0;
int activeMeetings = 0;
int i=0, j=0;
while (i < intervals.length && j < intervals.length)
if (starts[i] < ends[j])
activeMeetings ++;
i ++;
else
activeMeetings --;
j ++;
rooms = Math.max(rooms, activeMeetings);
return rooms;
参考文章:
http://buttercola.blogspot.com/2015/08/leetcode-meeting-rooms-ii.html
http://www.jyuan92.com/blog/leetcode-meeting-rooms-ii/
以上是关于LeetCode 253. Meeting Rooms II(会议室)的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 253: Meeting Rooms II