LeetCode 1353. Maximum Number of Events That Can Be Attended

原题链接在这里:https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/description/

题目:

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.

Example 2:

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

Constraints:

  • 1 <= events.length <= 105
  • events[i].length == 2
  • 1 <= startDayi <= endDayi <= 105

题解:

Sort the events based on start.

Have a minHeap to keep the end of event.

Incrementing the day from 1 to 100000, first poll the event that is endded before today d.

For all the event that starts today, add them into the minHeap.

If minHeap is not empay, greedy attend a event that is ending soon. res++, minHeap.poll().

Time Complexity: O(nlogn + d). n = events.length. d = 100000.

Space: O(n).

AC Java:

复制代码
 1 class Solution {
 2     public int maxEvents(int[][] events) {
 3         Arrays.sort(events, (a, b) -> Integer.compare(a[0], b[0]));
 4         PriorityQueue<Integer> minHeap = new PriorityQueue<>();
 5         int res = 0;
 6         int i = 0;
 7         int n = events.length;
 8         for(int d = 1; d <= 100000; d++){
 9             while(!minHeap.isEmpty() && minHeap.peek() < d){
10                 minHeap.poll();
11             }
12 
13             while(i < n && events[i][0] == d){
14                 minHeap.add(events[i++][1]);
15             }
16 
17             if(!minHeap.isEmpty()){
18                 minHeap.poll();
19                 res++;
20             }
21         }
22 
23         return res;
24     }
25 }
复制代码

类似Meeting Rooms II.

posted @   Dylan_Java_NYC  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示