数飞机
给出飞机的起飞和降落时间的列表,用 interval 序列表示. 请计算出天上同时最多有多少架飞机?
您在真实的面试中是否遇到过这个题?
Yes
样例
对于每架飞机的起降时间列表:[[1,10],[2,3],[5,8],[4,7]]
, 返回3
。
注意
标签
Expand
如果多架飞机降落和起飞在同一时刻,我们认为降落有优先权。
相关题目
Expand
解题思路:
用一个map记录每一时间点的降落和起飞的飞机数
比如[1,10] 用map记录为map[ 1 ]++1时刻多了一只飞机,map[ 10 ]--,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
if(airplanes==null||airplanes.size()==0) return 0;
Map<Integer, Integer> map = new HashMap<>();
int len = airplanes.size();
Set<Integer> set = new TreeSet<>();
for(int i=0;i<len;i++){
int s = airplanes.get(i).start;
int e = airplanes.get(i).end;
map.put(s,map.containsKey(s)?map.get(s)+1:1);
map.put(e,map.containsKey(e)?map.get(e)-1:-1);
set.add(s);
set.add(e);
}
int maxAirNo = Integer.MIN_VALUE;
int curcount = 0;
Iterator<Integer> tmp = set.iterator();
while(tmp.hasNext()){
curcount += map.get(tmp.next());
maxAirNo = Math.max(maxAirNo, curcount);
}
return maxAirNo;
}
}