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

lintcode:数飞机

时间:2016-04-03 11:44:04      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

数飞机

给出飞机的起飞和降落时间的列表,用 interval 序列表示. 请计算出天上同时最多有多少架飞机?

如果多架飞机降落和起飞在同一时刻,我们认为降落有优先权。

样例

对于每架飞机的起降时间列表:[[1,10],[2,3],[5,8],[4,7]], 返回3

解题

参考链接 

利用HashMap记录每个时刻的飞机数量

利用set记录时间点

最后对set 的每个时间点,找出连续时间点飞机数量和最大的那个时间段

/**
 * 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;
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        Set<Integer> set = new TreeSet<Integer>();// 记录此时刻的飞机数量
        for(int i =0;i<airplanes.size();i++){
            int s = airplanes.get(i).start;
            int e = airplanes.get(i).end;
            if(map.containsKey(s))
                map.put(s,map.get(s) + 1);// 空中的飞机 + 1
            else
                map.put(s,1);
            if(map.containsKey(e))
                map.put(e,map.get(e) - 1);// 空中飞机 - 1
            else
                map.put(e,-1);
            set.add(s);// 该时间点的飞机数 set是升序排序的
            set.add(e);
        }
        Iterator it = set.iterator();
        int maxAirNo = Integer.MIN_VALUE;  
        int curcount = 0;  
        Iterator<Integer> tmp = set.iterator(); 
        while(tmp.hasNext()){  
             curcount += map.get(tmp.next());  // 从最小时间点开始找出连续最长的飞机数和
             maxAirNo = Math.max(maxAirNo, curcount);  
        }  
         
        return maxAirNo;
    }
}

 

 

lintcode:数飞机

标签:

原文地址:http://www.cnblogs.com/theskulls/p/5349488.html

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