leetcode630——Course Schedule III

题目大意:给出n个课程的信息,每个课程信息是一个二维数组,表示课程的耗时和deadline,问最多能完成这些课程中的多少

分析:贪心法。贪心思想——按课程的deadline从小到大排序,因为越需要早点结束就意味着越需要尽快安排它被上完,当我们加入一个课程却发现上完它的时间超过了它的deadline时,就需要将已经安排的课程中最耗时的一个课程去掉,这一点需要用一个优先及队列来辅助存储。

代码:转载自https://blog.csdn.net/magicbean2/article/details/79089188

class Solution {
public:
    int scheduleCourse(vector<vector<int>>& courses) {
        sort(courses.begin(), courses.end(), [](vector<int> a, vector<int> b){return a[1] < b[1];});
        priority_queue<int> heap;
        int now = 0;                    // the current day
        for (int i = 0; i < courses.size(); ++i) {
            heap.push(courses[i][0]);   // push the time cost of courses[i]
            now += courses[i][0];
            if (now > courses[i][1]) {  // exceeds the deadlines, so we remove the one that is most time-consuming
                now -= heap.top();
                heap.pop();
            }
        }
        return heap.size();
    }
};

猜你喜欢

转载自blog.csdn.net/tzyshiwolaogongya/article/details/81188222
今日推荐