Given an list interval
, which are taking off and landing time of the flight. How many airplanes are there at most at the same time in the sky?
Example
Example 1:
Input: [(1, 10), (2, 3), (5, 8), (4, 7)]
Output: 3
Explanation:
The first airplane takes off at 1 and lands at 10.
The second ariplane takes off at 2 and lands at 3.
The third ariplane takes off at 5 and lands at 8.
The forth ariplane takes off at 4 and lands at 7.
During 5 to 6, there are three airplanes in the sky.
Example 2:
Input: [(1, 2), (2, 3), (3, 4)]
Output: 1
Explanation: Landing happen before taking off.
Notice
If landing and taking off of different planes happen at the same time, we consider landing should happen at first.
思路:用扫描线算法,头尾都是一个event,头是起飞,尾巴是降落,如果时间相等的时候,先把降落排前面,这样先计算下降的飞机,然后再计算起飞的;注意排序最后如果申请的是array,一定要用Collections.sort();
/**
* Definition of Interval:
* public classs Interval {
* int start, end;
* Interval(int start, int end) {
* this.start = start;
* this.end = end;
* }
* }
*/
public class Solution {
/**
* @param airplanes: An interval array
* @return: Count of airplanes are in the sky.
*/
private class Node {
public int time;
public int flag;
public Node(int time, int flag) {
this.time = time;
this.flag = flag;
}
}
public int countOfAirplanes(List<Interval> airplanes) {
int count = 0;
List<Node> list = new ArrayList<Node>();
for(Interval interval: airplanes) {
list.add(new Node(interval.start, 1));
list.add(new Node(interval.end, -1));
}
Collections.sort(list, (a, b) -> a.time != b.time ? a.time - b.time : a.flag - b.flag);
int maxplane = 0;
for(int i = 0; i < list.size(); i++) {
Node node = list.get(i);
if(node.flag == 1) {
count++;
} else {
count--;
}
maxplane = Math.max(maxplane, count);
}
return maxplane;
}
}
也可以用treemap来做, <Integer, Integer> 分别代表index和出现的次数 start +1, end -1, 然后for loop一下key,就是扫描,因为treemap的key是sorted;
/**
* Definition of Interval:
* public classs Interval {
* int start, end;
* Interval(int start, int end) {
* this.start = start;
* this.end = end;
* }
* }
*/
public class Solution {
/**
* @param airplanes: An interval array
* @return: Count of airplanes are in the sky.
*/
public int countOfAirplanes(List<Interval> airplanes) {
TreeMap<Integer, Integer> treemap = new TreeMap<>();
for(Interval interval: airplanes) {
treemap.put(interval.start, treemap.getOrDefault(interval.start, 0) + 1);
treemap.put(interval.end, treemap.getOrDefault(interval.end, 0) - 1);
}
int maxcount = 0;
int count = 0;
for(Integer key: treemap.keySet()) {
count += treemap.get(key);
maxcount = Math.max(maxcount, count);
}
return maxcount;
}
}