题目是meeting room ii但是要求最后的output是每一个room以及里面的meeting的intervals都要有,举个例子就是
// input : [3, 6], [6, 9], [5, 7]
// output: Room1 : [3, 6], [6, 9]
// Room2 : [5, 7]
http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=203781&page=1#pid2558839
My code:
public List<String> meetingRoom(List<Meeting> intervals) {
List<String> ret = new ArrayList<String>();
if (intervals == null || intervals.size() == 0) {
return ret;
}
Collections.sort(intervals, new Comparator<Meeting>() {
public int compare(Meeting i1, Meeting i2) {
return i1.start - i2.start;
}
});
PriorityQueue<Meeting> pq = new PriorityQueue<Meeting>(intervals.size(), new Comparator<Meeting>() {
public int compare(Meeting i1, Meeting i2) {
return i1.end - i2.end;
}
});
HashMap<Meeting, List<Meeting>> map = new HashMap<Meeting, List<Meeting>>();
pq.offer(intervals.get(0));
map.put(intervals.get(0), new ArrayList<Meeting>());
map.get(intervals.get(0)).add(new Meeting(intervals.get(0).start, intervals.get(0).end));
for (int i = 1; i < intervals.size(); i++) {
Meeting m = pq.poll();
if (m.end <= intervals.get(i).start) {
map.get(m).add(intervals.get(i));
m.end = intervals.get(i).end;
}
else {
map.put(intervals.get(i), new ArrayList<Meeting>());
map.get(intervals.get(i)).add(new Meeting(intervals.get(i).start, intervals.get(i).end));
pq.offer(intervals.get(i));
}
pq.offer(m);
}
while (!pq.isEmpty()) {
Meeting m = pq.poll();
String s = "[ ";
for (Meeting curr : map.get(m)) {
s += curr.toString() + " ";
}
s += " ]";
ret.add(s);
}
return ret;
}
class Meeting {
int start;
int end;
Meeting(int start, int end) {
this.start = start;
this.end = end;
}
public String toString() {
return "[" + start + ", " + end + "]";
}
}
注意, Heap 里面的 Meeting end 不断在变,所以,map 里面的List<Meeting>必须都是 deep copy
Heap 是 end 最小堆
首先对 List 按照start进行排序。
reference:
https://discuss.leetcode.com/topic/20958/ac-java-solution-using-min-heap
有一些改动
Anyway, Good luck, Richardo! — 09/28/2016