Interview Question - Meeting room (find the rooms)

题目是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 meetingRoom(List intervals) {
    List ret = new ArrayList();
    if (intervals == null || intervals.size() == 0) {
        return ret;
    }
    Collections.sort(intervals, new Comparator() {
        public int compare(Meeting i1, Meeting i2) {
            return i1.start - i2.start;
        }
    });
    
    PriorityQueue pq = new PriorityQueue(intervals.size(), new Comparator() {
        public int compare(Meeting i1, Meeting i2) {
            return i1.end - i2.end;
        }
    });
    HashMap> map = new HashMap>();
    pq.offer(intervals.get(0));
    map.put(intervals.get(0), new ArrayList());
    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());
            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必须都是 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

你可能感兴趣的:(Interview Question - Meeting room (find the rooms))