zoukankan      html  css  js  c++  java
  • Number of Airplanes in the Sky

    Given an interval list which are flying and landing time of the flight. How many airplanes are on the sky at most?

     Notice

    If landing and flying happens at the same time, we consider landing should happen at first.

    For interval list

    [
      [1,10],
      [2,3],
      [5,8],
      [4,7]
    ]
    

    Return 3

    扫描线 sweep line的第一题,求天空多最多有多少架飞机。扫描线最大的特点是给的数据是区间型。在操作之前需要先把区间数据做一个从前到后的排序。然后再从前向后扫描,对于区间的开始和结束会有一个操作。这之间的值没有处理的价值。比如对于这题,飞机起飞在天空的飞机多一架,落地则少一架。但是需要注意的是,如果同时有飞机在落地和起飞时,默认落地优先。所以在排序的时候落地优先。代码如下:

    """
    Definition of Interval.
    class Interval(object):
        def __init__(self, start, end):
            self.start = start
            self.end = end
    """
    class Solution:
        # @param airplanes, a list of Interval
        # @return an integer
        def countOfAirplanes(self, airplanes):
            if not airplanes:
                return 0
            maxNum = 0
            points = []
            for interval in airplanes:
                points.append((interval.start,1))
                points.append((interval.end,0))
            points.sort(key = lambda x: (x[0],x[1]))
            cur = 0
            for point in points:
                if point[1] == 1:
                    cur += 1
                    maxNum = max(maxNum, cur) 
                else:
                    cur -= 1
            
            return maxNum

    排序的时间复杂度为O(nlogn),扫描的时间复杂度为O(n)。空间复杂度为O(n)。所以最终的时间复杂度为O(nlogn),空间复杂度为O(n)。

  • 相关阅读:
    《独立网店经营十招招招制胜》
    行业礼品解决方案集
    北京第一礼品网
    ecshop网店系统+Ucenter用户中心+Cyask问答系统整合
    北京礼品在线入驻CRD核心商业区万达广场
    SEO中的关键字扩展
    礼问天下上线
    好网推荐
    北京礼品在线夏日礼の尚礼品促销第二波
    广告管理中的热点问题
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5596915.html
Copyright © 2011-2022 走看看