博客
关于我
【Lintcode】919. Meeting Rooms II
阅读量:202 次
发布时间:2019-02-28

本文共 1688 字,大约阅读时间需要 5 分钟。

给定一系列会议的开始和结束时间组成的数组,会议时长都是大于0的。问最少需要多少个会议室。

解决这个问题的关键在于使用扫描线算法。具体步骤如下:

  • 事件处理:将每个会议的开始和结束时间分别记录为两个事件。开始事件用+1标记,结束事件用-1标记。

  • 排序事件:将所有事件按照时间排序。如果时间相同,则结束事件排在前面(因为结束事件处理完后,才会处理开始事件,这样可以正确计算当前活动数量)。

  • 统计活动数:遍历排序后的事件列表,逐个处理每个事件,更新当前活动数。记录当前活动数的最大值,这个最大值即为最少需要的会议室数。

  • 代码实现

    import java.util.ArrayList;import java.util.List;public class Solution {    class Pair {        int time;        int flag;        public Pair(int time, int flag) {            this.time = time;            this.flag = flag;        }    }    public int minMeetingRooms(List
    intervals) { if (intervals == null || intervals.isEmpty()) { return 0; } List
    list = new ArrayList<>(); for (Interval interval : intervals) { list.add(new Pair(interval.start, 1)); list.add(new Pair(interval.end, 0)); } list.sort((p1, p2) -> { if (p1.time != p2.time) { return Integer.compare(p1.time, p2.time); } else { return Integer.compare(p1.flag, p2.flag); } }); int res = 0, count = 0; for (Pair pair : list) { if (pair.flag == 1) { count++; } else { count--; } res = Math.max(res, count); } return res; } class Interval { int start; int end; public Interval(int start, int end) { this.start = start; this.end = end; } }}

    时间复杂度

    • 时间复杂度:O(n log n),排序时间复杂度主要为O(n log n)。
    • 空间复杂度:O(n),用于存储事件列表。

    算法正确性证明

    • 算法正确性:算法得到同一时间点的最大活动数,这个数即为最少需要的会议室数。通过直接构造方案,使用这个数量的会议室,可以安排所有会议,确保没有时间冲突。因此,算法正确。

    通过上述方法,可以有效地解决会议室安排问题,确保最少需要的会议室数正确无误。

    转载地址:http://xzcs.baihongyu.com/

    你可能感兴趣的文章
    POJ 3253 Fence Repair C++ STL multiset 可解 (同51nod 1117 聪明的木匠)
    查看>>
    poj 3262 Protecting the Flowers 贪心
    查看>>
    poj 3264(简单线段树)
    查看>>
    poj 3277 线段树
    查看>>
    POJ 3349 Snowflake Snow Snowflakes
    查看>>
    poj 3422 Kaka's Matrix Travels (费用流 + 拆点)
    查看>>
    Qt笔记——官方文档全局定义(二)Functions函数
    查看>>
    POJ 3468 A Simple Problem with Integers
    查看>>
    poj 3468 A Simple Problem with Integers 降维线段树
    查看>>
    poj 3468 A Simple Problem with Integers(线段树 插线问线)
    查看>>
    poj 3485 区间选点
    查看>>
    poj 3518 Prime Gap
    查看>>
    poj 3539 Elevator——同余类bfs
    查看>>
    poj 3628 Bookshelf 2
    查看>>
    Qt笔记——官方文档全局定义(一)Types数据类型
    查看>>
    POJ 3670 DP LIS?
    查看>>
    POJ 3683 Priest John's Busiest Day (算竞进阶习题)
    查看>>
    POJ 3988 Selecting courses
    查看>>
    POJ 4020 NEERC John's inversion 贪心+归并求逆序对
    查看>>
    poj 4044 Score Sequence(暴力)
    查看>>