线扫描问题
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.
Example
For interval list
[
(1,10),
(2,3),
(5,8),
(4,7)
]
Return 3
/**
* Definition of Interval:
* public classs Interval {
* int start, end;
* Interval(int start, int end) {
* this.start = start;
* this.end = end;
* }
* }
*/
class Point {
int time;
int flag;
public Point(int time, int flag) {
this.time = time;
this.flag = flag;
}
}
public class Solution {
/**
* @param airplanes: 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;
}
Comparator<Point> cmp = new Comparator<Point>() {
public int compare(Point p1, Point p2) {
if (p1.time == p2.time) {
return p1.flag - p2.flag;
}
return p1.time - p2.time;
}
};
List<Point> list = new ArrayList<>();
for (int i = 0; i < airplanes.size(); i++) {
Interval val = airplanes.get(i);
list.add(new Point(val.start, 1));
list.add(new Point(val.end, 0));
}
Collections.sort(list, cmp);
int count = 0, max = Integer.MIN_VALUE;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).flag == 1) {
count++;
} else {
count--;
}
max = Math.max(max, count);
}
return max;
}
}