Blage's Coding Blage's Coding
Home
算法
  • 手写Spring
  • SSM
  • SpringBoot
  • JavaWeb
  • JAVA基础
  • 容器
  • Netty

    • IO模型
    • Netty初级
    • Netty原理
  • JVM
  • JUC
  • Redis基础
  • 源码分析
  • 实战应用
  • 单机缓存
  • MySQL

    • 基础部分
    • 实战与处理方案
    • 面试
  • ORM框架

    • Mybatis
    • Mybatis_Plus
  • SpringCloudAlibaba
  • MQ消息队列
  • Nginx
  • Elasticsearch
  • Gateway
  • Xxl-job
  • Feign
  • Eureka
  • 面试
  • 工具
  • 项目
  • 关于
🌏本站
🧸GitHub (opens new window)
Home
算法
  • 手写Spring
  • SSM
  • SpringBoot
  • JavaWeb
  • JAVA基础
  • 容器
  • Netty

    • IO模型
    • Netty初级
    • Netty原理
  • JVM
  • JUC
  • Redis基础
  • 源码分析
  • 实战应用
  • 单机缓存
  • MySQL

    • 基础部分
    • 实战与处理方案
    • 面试
  • ORM框架

    • Mybatis
    • Mybatis_Plus
  • SpringCloudAlibaba
  • MQ消息队列
  • Nginx
  • Elasticsearch
  • Gateway
  • Xxl-job
  • Feign
  • Eureka
  • 面试
  • 工具
  • 项目
  • 关于
🌏本站
🧸GitHub (opens new window)
  • 数组

  • 链表

  • 字符串

  • 二叉树

  • 动态规划

  • 深搜回溯

  • 数学贪心

    • LCP 33. 蓄水
    • 6455. 使所有字符相等的最小成本
    • 55. 跳跃游戏
    • 2517. 礼盒的最大甜蜜度
    • 2611. 老鼠和奶酪
    • 6449. 收集巧克力
    • 1401. 圆和矩形是否有重叠
    • 2178. 拆分成最多数目的正偶数之和
    • 376. 摆动序列
    • 649. Dota2 参议院
    • 630. 课程表 III
      • 1.贪心+优先队列
    • 2136. 全部开花的最早一天
    • 2731. 移动机器人
  • 堆栈队列

  • 前缀和

  • 算法设计

  • 位运算

  • WA

  • 算法
  • 数学贪心
phan
2023-09-11
目录

630. 课程表 III

# 630. 课程表 III (opens new window)

# 1.贪心+优先队列

解题思路:在截止时间的限制下,维护一个总耗时最短的课程序列。

  • 对所有课程按截止时间进行排序
  • 创建一个降序的优先级队列
  • 每次遍历时算法如下:
    • 当前课程时间加入“当前时间”的总和
    • 如果“当前时间”已经超过当前课程的截止时间,则从队列中删除持续时间最长的课程。

从队列中删除最长时间的课程,可以保证当前已修课程总耗时最短,但如何证明删除后已满足的最大课程数量依然保持不变?具体来说,假设当前课程(cost,limit),那么如何证明 curr+cost-max(queue) <limit?证明如下:

显然,在遍历过程中 curr < limit;假设 k=max(curr,cost),那么一定有 curr + cost - k <= curr <limit。相当于删除耗时最大的课程。

✨多维贪心技巧:优先对时刻、数量等限制条件排序。另一维可以通过数据存取方式体现贪心策略。

class Solution {
    public int scheduleCourse(int[][] courses) {
       Arrays.sort(courses,new Comparator<int[]>(){
            public int compare(int[] a,int[] b){
                if(a[1]!=b[1]) return a[1]-b[1];
                else return a[0]-b[0];
            }
        });
        PriorityQueue<Integer> queue=new PriorityQueue<>(new Comparator<Integer>(){
            public int compare(Integer a,Integer b){
                return b-a;
            }
        });
        int step=0;
        int res=0,curr=0;
        for(int i=0;i<courses.length;i++){
            queue.offer(courses[i][0]);
            curr+=courses[i][0];
            step++;
            if(curr>courses[i][1]){
                    curr-=queue.poll();
                    step--;
            }
            res=Math.max(res,step);
        }
        return res;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
编辑 (opens new window)
#Leetcode
上次更新: 2023/12/15, 15:49:57
649. Dota2 参议院
2136. 全部开花的最早一天

← 649. Dota2 参议院 2136. 全部开花的最早一天→

Theme by Vdoing | Copyright © 2023-2024 blageCoder
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式