?LeetCode刷題實(shí)戰(zhàn)630:課程表 III
There are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken continuously for durationi days and must be finished before or on lastDayi.
You will start on the 1st day and you cannot take two or more courses simultaneously.
Return the maximum number of courses that you can take.
這里有 n 門不同的在線課程,按從 1 到 n 編號(hào)。給你一個(gè)數(shù)組 courses ,其中 courses[i] = [durationi, lastDayi] 表示第 i 門課將會(huì) 持續(xù) 上 durationi 天課,并且必須在不晚于 lastDayi 的時(shí)候完成。
你的學(xué)期從第 1 天開始。且不能同時(shí)修讀兩門及兩門以上的課程。
返回你最多可以修讀的課程數(shù)目。
示例 1:
輸入:courses = [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
輸出:3
解釋:
這里一共有 4 門課程,但是你最多可以修 3 門:
首先,修第 1 門課,耗費(fèi) 100 天,在第 100 天完成,在第 101 天開始下門課。
第二,修第 3 門課,耗費(fèi) 1000 天,在第 1100 天完成,在第 1101 天開始下門課程。
第三,修第 2 門課,耗時(shí) 200 天,在第 1300 天完成。
第 4 門課現(xiàn)在不能修,因?yàn)閷?huì)在第 3300 天完成它,這已經(jīng)超出了關(guān)閉日期。
示例 2:
輸入:courses = [[1,2]]
輸出:1
示例 3:
輸入:courses = [[3,2],[4,3]]
輸出:0
主要思路:
考慮兩個(gè)因素,先考慮結(jié)束時(shí)間,其次考慮時(shí)間
優(yōu)先選取最快要結(jié)束的課程(2 5 ,3 6)
如果當(dāng)前課程時(shí)間沖突(完成時(shí)間大于結(jié)束時(shí)間),那么就從已經(jīng)完成的課程中(包括當(dāng)前課程)找一個(gè)需要時(shí)間最長的刪除(當(dāng)前課程優(yōu)于時(shí)間長的課程)。
class?Solution?{
public:
// 優(yōu)先學(xué)習(xí)最快要結(jié)束的課程,如果課程沖突,則將已經(jīng)上過的持續(xù)時(shí)間最長的課程排除
????int?scheduleCourse(vector<vector<int>>& courses)?{
????????priority_queue<int> pq;
????????int?n=courses.size();
????????// 按照結(jié)束時(shí)間排序
????????sort(courses.begin(),courses.end(),[](const?vector<int>& l,const?vector<int>& r){
????????????if(l[1]==r[1])
????????????????return?l[0]0];
????????????return?l[1]1];
????????});
????????int?sum=0;
????????for(int?i=0;i????????????pq.push(courses[i][0]);
????????????sum+=courses[i][0];
????????????// 如果沖突,將前邊時(shí)間最長的課程刪去
????????????if(sum>courses[i][1])
????????????????sum-=pq.top(),pq.pop();
????????}
????????return?pq.size();
????}
};
