Leetcode: 1353. Maximum Number of Events That Can Be Attended

Description

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

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.

分析

刚开始,sorted(events, key=lambda x: x[::-1]) 的方式排序,总是错误。后面改用新的排序方式,即 x[1] -x[0] 最小的排在前面,还是会出错。
中间陆续试用 好几个算法, 结果还是 ❌ ❌ ❌ 。
最后该用什么了现在的算法(速度上战胜 96% 的 submission),具体如下
将所有的 events 按 endDate 归类,
优先处理 endDate 那一类,
处理某个 endDate 时,优先处理 startDate 大的 event。 每次碰到一个 startdate, 先看下能放到 day 去 attend。 如果可以,就把 day --, 如果 day 等于下一个 enddate 类的 enddata。则将当前的没有处理完的数据和下一个 enddate 数据放在一起排序,继续循环优先处理 startdate 大的 event 



code

import collections
import heapq

class Solution(object):
    def maxEvents(self, events):
        """
        :type events: List[List[int]]
        :rtype: int
        """
        # find solution for the shortest event !!
        counter = collections.defaultdict(list)
        for start, end in events:
            counter[end].append(-start)
            
        ends = sorted(counter.keys())
        pq, count, nextP, preE = [], 0, ends[-1], 0
        
        for turn in range(len(ends)-1, -1, -1):
            if turn > 0:
                preE = ends[turn-1]
            else:
                preE = 0
            if len(pq) == 0:
                pq = sorted(counter[ends[turn]])
            else:
                
                for start in counter[ends[turn]]:
                    heapq.heappush(pq, start)
                    
            nextP = min(nextP, ends[turn])
            while pq:
                v = heapq.heappop(pq) * -1
                if nextP >= v:
                    count += 1
                    nextP -= 1
                if nextP == preE:
                    break
        
        return count

总结

  • 本题的 难度是 medium, 但是提交通过率 只有 30.6 % 。算是 medium 难度题目中的 佼佼者
    
posted @ 2021-03-27 18:05  tmortred  阅读(45)  评论(0编辑  收藏  举报