Given an interval list which is flying and landing time of the flight. How many airplanes is on the sky?
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]]
Return3
Analysis:
This question can be interval from 1-23 per check whether it contains that number. But there is a more ingenious approach to this problem:
Divide all the interval into two parts, take-off and landing parts. Add each part to the list, then sort them by time and then remove them all. If it is takeoff, count++, if landed, Count--。 The solution is not very peculiar.
If I were an interviewer, I would probably ask in a different way: give a bunch of intervals, find out the maximum number of overlap, so that the first solution is directly not the most optimal solution.
1 /**2 * Definition of Interval:3 * Public classs Interval {4 * int start, end;5 * Interval (int start, int end) {6 * This.start = start;7 * this.end = end;8 * }9 */Ten One Public classSolution { A /** - * @param intervals:an interval array - * @return: Count of Airplanes is in the sky. the */ - Public intCountofairplanes (list<interval>airplanes) { - -list<point> list =NewArraylist<point> (Airplanes.size () *2); + for(Interval i:airplanes) { -List.add (NewPoint (I.start,1)); +List.add (NewPoint (I.end,0)); A } at - Collections.sort (list); - intCount =0, ans =0; - for(Point p:list) { - if(P.flag = =1) count++; - Elsecount--; inAns =Math.max (ans, count); - } to + returnans; - } the } * $ classPoint implements Comparable<point> {Panax Notoginseng intTime ; - intFlag; the +Point (intTints) { A This. Time =T; the This. Flag =s; + } - $ @Override $ Public intcompareTo (point p) { - if( This. Time = =p.time) - return This. Flag-P.flag; the Else - return This. Time-P.time;Wuyi } the}
Number of airplanes in the Sky