贪心-Course Schedule III

2020-02-01 21:37:39

问题描述

问题求解

对于课程来说截止时间在前面的肯定需要优先安排,所以首先需要将courses按照deadline进行排序。

然后只需要不断的加入当前的课程即可,如果时间超过了deadline,那么就将之前最耗时的课程剔除即可。

为什么剔除了耗时的就一定可以不超时呢?

1)最耗时的是当前的课程,那么直接删除,状态还原到上一层,不超时;

2)最耗时的不是当前的课程,那么删除耗时的,再加上新增的必不会超过prev_time,也就必不会超时;

    public int scheduleCourse(int[][] courses) {
        Arrays.sort(courses, new Comparator<int[]>(){
            public int compare(int[] o1, int[] o2) {
                return o1[1] - o2[1];
            }
        });
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        int time = 0;
        for (int[] c : courses) {
            time += c[0];
            pq.add(-c[0]);
            if (time > c[1]) {
                time += pq.poll();
            }
        }
        return pq.size();
    }

  

原文地址:https://www.cnblogs.com/hyserendipity/p/12250295.html