【LeetCode 1353】 Maximum Number of Events That Can Be Attended

题目描述

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
# 思路
贪心。会议按照开始时间从小到大排序,遍历天数,每次把当前可以参加的会议加入到优先队列,会议结束时间从小到大排序,每次选择结束时间最早的会议参加。
# 代码
```c
class Solution {
public:
   int maxEvents(vector<vector<int>>& events) {
       sort(events.begin(), events.end(), cmp);
       priority_queue<int, vector<int>, greater<int> > pq;
       int day = 0;
       int index = 0;
       int res = 0;
       int len = events.size();
       
       while(day <= 100000) {
           if (pq.empty() && index >= len) break;
           while(index<len && events[index][0]<=day) pq.push(events[index++][1]);
           while(!pq.empty() && pq.top()<day) pq.pop();
           if (!pq.empty()) {
               pq.pop();
               res++;
           }
           day++;
       }
       return res;
   }

private:
   static bool cmp(vector<int>& A, vector<int>& B) {
       if (A[0] == B[0]) return A[1] < B[1];
       return A[0] < B[0];
   }
};

怎么办啊。。。。
感受到找不到工作的恐惧。
555

发布了323 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/105066912
今日推荐