LeetCode1353. 最多可以參加的會議數目

1353. Maximum Number of Events That Can Be Attended

[Medium]

Given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.

You can attend an event i at any day d where startTimei <= d <= endTimei. Notice that you can only attend one event at any time d.

Return the maximum number of events you can attend.

Example 1:

在這裏插入圖片描述

Input: events = [[1,2],[2,3],[3,4]]
Output: 3
Explanation: You can attend all the three events.
One way to attend them all is as shown.
Attend the first event on day 1.
Attend the second event on day 2.
Attend the third event on day 3.

Example 2:

Input: events= [[1,2],[2,3],[3,4],[1,2]]
Output: 4

Example 3:

Input: events = [[1,4],[4,4],[2,2],[3,4],[1,1]]
Output: 4

Example 4:

Input: events = [[1,100000]]
Output: 1

Example 5:

Input: events = [[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7]]
Output: 7

Constraints:

  • 1 <= events.length <= 10^5
  • events[i].length == 2
  • 1 <= events[i][0] <= events[i][1] <= 10^5

題目:給你一個數組 events,其中 events[i] = [startDayi, endDayi] ,表示會議 i 開始於 startDayi ,結束於 endDayi 。你可以在滿足 startDayi <= d <= endDayi 中的任意一天 d 參加會議 i 。注意,一天只能參加一個會議。請你返回你可以參加的 最大 會議數目。

思路:參考lee215。首先對events按照startDayi升序排列,然後按照貪心的原則優先安排endTime 小的event

工程代碼下載

class Solution {
public:
    int maxEvents(vector<vector<int>>& events) {
        // 以events[i]的endTime作爲依據構建小頂堆
        priority_queue<int, vector<int>, greater<int>> pq;
        sort(events.begin(), events.end());
        int n = events.size();
        int res = 0;

        // 判斷第d天的情況
        for(int d = 1, i = 0; d <= 100000; ++d){
            // 排除隊列中endTime小於d的所有事件
            while(!pq.empty() && pq.top() < d)
                pq.pop();
            // 將startTime爲d的事件對應的endTime添加進隊列
            while(i < n && events[i][0] == d)
                pq.push(events[i++][1]);
            // 如果隊列非空,則按照貪心的準則在第d天安排隊列中endTime最小的事件
            if(!pq.empty()){
                res += 1;
                pq.pop();
            }
        }

        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章