Friday, July 21, 2017

Leetcode: Meeting Room II

July 21, 2017

Plan to study the algorithm Meeting Room II.

Here is the discussion to review:
The idea is seen in the blog on segment fault. Link is here.

这题的思路和Rearrange array to certain distance很像,我们要用贪心法,即从第一个时间段开始,选择下一个最近不冲突的时间段,再选择下一个最近不冲突的时间段,直到没有更多。然后如果有剩余时间段,开始为第二个房间安排,选择最早的时间段,再选择下一个最近不冲突的时间段,直到没有更多,如果还有剩余时间段,则开辟第三个房间,以此类推。这里的技巧是我们不一定要遍历这么多遍,我们实际上可以一次遍历的时候就记录下,比如第一个时间段我们放入房间1,然后第二个时间段,如果和房间1的结束时间不冲突,就放入房间1,否则开辟一个房间2。然后第三个时间段,如果和房间1或者房间2的结束时间不冲突,就放入房间1或者2,否则开辟一个房间3,依次类推,最后统计开辟了多少房间。对于每个房间,我们只要记录其结束时间就行了,这里我们查找不冲突房间时,只要找结束时间最早的那个房间。
这里还有一个技巧,如果我们把这些房间当作List来管理,每次查询需要O(N)时间,如果我们用堆来管理,可以用logN时间找到时间最早结束的房间。


Here is the Java code to review.

Go  over the leetcode discussion and try to find out good ideas. Plan to study code provided by high reputation engineer Su Yong, code is here. And plan to spend time to read ofLucas to explain the Su Yong's design in detail in this discussion link.


No comments:

Post a Comment