You are 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. 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.
思路:这题是贪心算法,按照start排序之后,优先做deadline最早的活,扫描day,然后把所有满足trigger event的endday丢入pq中排序。然后把超过today的dueday的event丢掉,每次poll出来一个,然后扫描下一天。nlogn;
class Solution {
public int maxEvents(int[][] events) {
Arrays.sort(events, (a, b) -> (a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]));
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
int i = 0;
int res = 0;
for(int day = 1; day <= 100000; day++) {
while(i < events.length && events[i][0] <= day) {
pq.offer(events[i][1]);
i++;
}
// 做完之后,要把pq里面,deadline超过今天的全部给踢掉;
while(!pq.isEmpty() && pq.peek() < day) {
pq.poll();
}
if(!pq.isEmpty()) {
pq.poll();
res++;
}
}
return res;
}
}

给定一个数组,其中每个事件都有开始和结束时间。你可以从任何一天开始并结束一个事件,但一次只能参加一个。返回最多可以参加的事件数量。问题可以通过贪心算法解决,按事件开始时间排序,优先选择结束时间最早的事件。
771

被折叠的 条评论
为什么被折叠?



