Number of Airplanes in the Sky
Posted Sheryl Wang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)。
以上是关于Number of Airplanes in the Sky的主要内容,如果未能解决你的问题,请参考以下文章
[LintCode] Number of Airplanes in the Sky
lintcode-medium-Number of Airplanes in the Sky
number field is the union of the set of all strings and the set of all numbers. The set of things th