您的位置:首页 > 大数据 > 人工智能

Number of Airplanes in the Sky

2016-07-20 23:18 525 查看
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


分析:

这题可以从1-23逐个check是否interval含有那个数。但是这题有一个更巧妙的方法:

把所有的interval分成两个部分,起飞部分和落地部分。把每个部分都加在LIST里面,然后按照时间排序,然后一一取出。如果是起飞,count++, 如果落地,count--。这个解法是不是很奇特。

如果我是面试官,我可能会换一种方式问:给一堆intervals,找出overlap最多的个数,这样,第一种解法就直接不能最为最优解了。

/**
* Definition of Interval:
* public classs Interval {
*     int start, end;
*     Interval(int start, int end) {
*         this.start = start;
*         this.end = end;
*     }
*/

public class Solution {
/**
* @param intervals: An interval array
* @return: Count of airplanes are in the sky.
*/
public int countOfAirplanes(List<Interval> airplanes) {

List<Point> list = new ArrayList<Point>(airplanes.size()*2);
for(Interval i : airplanes){
list.add(new Point(i.start, 1));
list.add(new Point(i.end, 0));
}

Collections.sort(list);
int count = 0, ans = 0;
for(Point p : list){
if(p.flag == 1) count++;
else count--;
ans = Math.max(ans, count);
}

return ans;
}
}

class Point implements Comparable<Point> {
int time;
int flag;

Point(int t, int s) {
this.time = t;
this.flag = s;
}

@Override
public int compareTo(Point p) {
if (this.time == p.time)
return this.flag - p.flag;
else
return this.time - p.time;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: