zoukankan      html  css  js  c++  java
  • 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 难度题目中的 佼佼者
      
  • 相关阅读:
    计算fibonacci数(多种方法)
    数组求和(两种方法)
    C语言二级指针(指向指针的指针)
    唯品会海量实时OLAP分析技术升级之路
    hive 调优(一)coding调优
    supsplk 服务器被植入木马 挖矿 cpu使用 700%
    OPTS参数设置
    Yarn 内存分配管理机制及相关参数配置
    hive on tez 任务失败
    hive 调优(三)tez优化
  • 原文地址:https://www.cnblogs.com/tmortred/p/14586504.html
Copyright © 2011-2022 走看看