LintCode --number-of-airplanes-in-the-sky(数飞机)
原题链接:http://www.lintcode.com/zh-cn/problem/number-of-airplanes-in-the-sky/
给出飞机的起飞和降落时间的列表,用 interval 序列表示. 请计算出天上同时最多有多少架飞机?
样例
对于每架飞机的起降时间列表:[[1,10],[2,3],[5,8],[4,7]]
, 返回3
。
注意
如果多架飞机降落和起飞在同一时刻,我们认为降落有优先权。
分析:
新建一个数组,下标为飞机起飞则为1,降落则为-1。然后新数组转化为最大子序列和问题。
时间复杂度 O(n+m),n为数组长度,m为降落的最大时间点。
代码(Python、C++、Java):
"""
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):
# write your code here
length = len(airplanes)
if length <= 1:
return length
max = airplanes[0].end
for i in range(length):
if airplanes[i].end > max:
max = airplanes[i].end
count = (max+1) * [0]
for i in range(length):
count[airplanes[i].start] = count[airplanes[i].start] + 1
count[airplanes[i].end] = count[airplanes[i].end] - 1
res = 1
t = 0
for i in range(max):
t = t + count[i]
if t < 0:
t = 0
if t > res:
res = t
return res
/**
* Definition of Interval:
* classs Interval {
* int start, end;
* Interval(int start, int end) {
* this->start = start;
* this->end = end;
* }
*/
class Solution {
public:
/**
* @param intervals: An interval array
* @return: Count of airplanes are in the sky.
*/
int countOfAirplanes(vector<Interval> &airplanes) {
// write your code here
int n = airplanes.size();
if (n <= 1) return n;
int max = airplanes[0].end;
for (int i = 0; i < n; i++){
if (airplanes[i].end > max)
max = airplanes[i].end;
}
int count[max+1+10];
/**
* Definition of Interval:
* public classs Interval {
* int start, end;
* Interval(int start, int end) {
* this.start = start;
* this.end = end;
* }
*/
class Solution {
/**
* @param intervals: An interval array
* @return: Count of airplanes are in the sky.
*/
public int countOfAirplanes(List<Interval> airplanes) {
// write your code here
int n = airplanes.size();
if (n <= 1) return n;
int max = airplanes.get(0).end;
for (int i = 0; i < n; i++)
if (airplanes.get(i).end > max)
max = airplanes.get(i).end;
int [] count = new int [max+1+10];
for (int i = 0; i < max ; i++)
count[i] = 0;
for (int i = 0; i < n; i++){
count[airplanes.get(i).start] += 1;
count[airplanes.get(i).end] -= 1;
}
int res = 0, t = 0;
for (int i = 0; i < max; i++){
t += count[i];
if (t < 0) t = 0;
if (t > res) res = t;
}
return res;
}
}