[leetcode] 1353。参加できるイベントの最大数

説明

events [i] = [startDayi、endDayi]であるイベントの配列が与えられます。すべてのイベントiはstartDayiで始まり、endDayiで終わります。

startTimei <= d <= endTimeiである任意の日dにイベントiに参加できます。d。一度に参加できるイベントは1つだけであることに注意してください。

参加できるイベントの最大数を返します。

例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.

例2:

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

例3:

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

例4:

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

例5:

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

制約:

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

分析

質問の意味は次のとおりです。いくつかの間隔[si、ei]で、各時間単位は1つのタスクしか完了できず、タスクを完了するための要件はsi <= i <= eiであり、タスクの数を尋ねます。せいぜい完了できます。
ヒープを使用する他の人の実装を参照し、最初にイベントを並べ替え、イベントの最大値nを見つけてから、1からn + 1までトラバースします。トラバースしたiについては、iで始まるイベントを見つけてから追加します。 endDayiヒープ内で、最後にi未満の数値を削除すると、残りの数値endはi以上になります。空でない場合は、要件を満たすイベントが見つかったことを意味し、resが更新されます。

コード

class Solution:
    def maxEvents(self, events: List[List[int]]) -> int:
        events.sort()
        res=0
        n=0
        for i,j in events:
            n=max(n,i,j)
        end=[]
        for i in range(1,n+1):
            while(events and events[0][0]==i):
                heapq.heappush(end,events.pop(0)[1])
            while(end and end[0]<i):
                heapq.heappop(end)
            if(end):
                heapq.heappop(end)
                res+=1
                
        return res

参照

貪欲なタイムアウト、公式の使用済みヒープを参照

おすすめ

転載: blog.csdn.net/w5688414/article/details/115269298