Greedy Algorithm

贪心算法的定义:

Greedy Algorithm_第1张图片

Greedy Algorithm_第2张图片

经典问题:课程安排

Leetcode 630

Greedy Algorithm_第3张图片

伪代码:

Greedy Algorithm_第4张图片

代码实现:

class Solution {
public:
    int scheduleCourse(vector>& courses) {
        sort(courses.begin(), courses.end(), [](vector a, vector b){return a[1] < b[1];});
        priority_queue heap;
        int now = 0;
        for (int i = 0; i < courses.size(); ++ i)
        {
            heap.push(courses[i][0]);
            now += courses[i][0];
            if (now > courses[i][1])
                now -= heap.top(), heap.pop();
        }
        return heap.size();
    }
};





你可能感兴趣的:(算法)