LeetCode 630 课程表

题目描述

这里有 n 门不同的在线课程,他们按从 1 到 n 编号。每一门课程有一定的持续上课时间(课程时间)t 以及关闭时间第 d 天。一门课要持续学习 t 天直到第 d 天时要完成,你将会从第 1 天开始。

给出 n 个在线课程用 (t, d) 对表示。你的任务是找出最多可以修几门课。

 

示例:

输入: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
输出: 3
解释: 
这里一共有 4 门课程, 但是你最多可以修 3 门:
首先, 修第一门课时, 它要耗费 100 天,你会在第 100 天完成, 在第 101 天准备下门课。
第二, 修第三门课时, 它会耗费 1000 天,所以你将在第 1100 天的时候完成它, 以及在第 1101 天开始准备下门课程。
第三, 修第二门课时, 它会耗时 200 天,所以你将会在第 1300 天时完成它。
第四门课现在不能修,因为你将会在第 3300 天完成它,这已经超出了关闭日期。

 

提示:

  1. 整数 1 <= d, t, n <= 10,000 。
  2. 你不能同时修两门课程。

 

解题思路:先按照每个课程结束的时间进行从小到大的排序,然后建一个大根堆,将每个课程的持续时间一次加入大根堆中,若发现总时间超过了这个课程的结束时间,则从堆中弹出持续时间最长的课程,遍历整个课程,最终堆的大小就是最多能上多少课程。

    public class Com2 implements Comparator<Integer>
    {
        public int compare(Integer o1,Integer o2)
        {
            return o2-o1;
        }    
    }
    public class Com1 implements Comparator<Integer[]>
    {
        public int compare(Integer[] a,Integer[] b)
        {
            return a[1]-b[1];
        }
    }
    public int scheduleCourse(int[][] courses) {
        Integer[][] course=new Integer[courses.length][courses[0].length];
        for(int i=0;i<courses.length;i++)
        {
            for(int j=0;j<courses[0].length;j++)
            {
                course[i][j]=courses[i][j];
            }
        }
        Arrays.sort(course,new Com1());
        PriorityQueue<Integer> heap=new PriorityQueue<>(new Com2());
        int cur=0;
        for(int i=0;i<course.length;i++)
        {
            heap.add(course[i][0]);
            cur+=course[i][0];
            if(cur>course[i][1])
            {
                cur-=heap.peek();
                heap.poll();
            }
        }
        return heap.size();
    }

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值