码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Number of Airplanes in the Sky

时间:2016-04-02 08:25:54      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

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 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;
        
        ArrayList<point> list = new ArrayList<point>();
        
        for(Interval interval: airplanes){
            list.add(new point(interval.start, 1));
            list.add(new point(interval.end, 0));
        }
        
        Collections.sort(list, new Comparator<point>(){
            public int compare(point p1, point p2){
                if(p1.time == p2.time){
                    return p1.flag - p2.flag;
                }
                else{
                    return p1.time - p2.time;
                }
            } 
        });
        
        int count = 0;
        int ans = 0;
        
        for(point p: list){
            if(p.flag == 1)
                count++;
            else
                count--;
            
            ans = Math.max(ans, count);
        }
        
        return ans;
    }
    
    class point{
        int time;
        int flag;
        
        public point(int time, int flag){
            this.time = time;
            this.flag = flag;
        }
    }
    
}

 

lintcode-medium-Number of Airplanes in the Sky

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5346865.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!