April 11,2021 leetcode 会议室题目 贪心算法

本文介绍了一种高效的算法,用于解决会议室分配问题。通过使用最小堆来跟踪会议结束时间,并对会议区间进行排序,确保了最少数量的会议室被使用。此算法适用于需要优化资源调度的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

class Solution {
public int minMeetingRooms(int[][] intervals) {

    //Check for the base case. IF there are no intervals, return 0
    if (intervals.length == 0) {
        return 0;
    }
    //Min heap 最小堆
    PriorityQueue<INteger> allocator =
        new PriorityQueue<INterger>(
            intervals.length,
            new Comparator<Interger>() {
                public int compare(Integer a, Integer b) {
                    return a - b;
                }
            });
    //Sort the intervals by start time
    Array.sort(
        intervals,
        new Comparator<int[]>() {
            public int compare(final int[] a, final int[] b) {
                return a[0] - b[0];    
            }
        });
    
    //add the first meeting
    allocator.add(intervals[0][1]);

    //Iterate over remaining intervals
    for (int i = 1; i < intervals.length; i++) {
        // If the room due to free up the earliest is free, assign that room to this meeting.
        if (intervals[i][0] >= allocator.peek()) {
            allocator.poll();
        }

        // If a new room is to be saas=igned, then also we add to the heap,
        // If an old room is allocated, then also we have to add to the heap with updated end time.
        allocator.add(intervals[i][1]);
    }

    // The size of the heap tells us minimum rooms required for all the meeting.
    return allocator.length;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值