lintcode(391)数飞机

描述:

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

样例:

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

思路:

统计每个时刻起飞降落的数量,最后累加,要对时间进行排序,按照时间先后读取数据,用hashset去重

/**
 * 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
        int result = 0;
        HashMap<Integer , Integer> record = new HashMap<Integer , Integer>();
        HashSet<Integer> count = new HashSet<Integer>();
        for(int i = 0;i<airplanes.size();i++){
            int start = airplanes.get(i).start;
            int end = airplanes.get(i).end;
            if(record.containsKey(start)){
                record.put(start , record.get(start) + 1);
            }else{
                record.put(start ,  1);
            }
            if(record.containsKey(end)){
                record.put(end , record.get(end) - 1);
            }else{
                record.put(end ,  - 1);
            }
            
            count.add(start);
            count.add(end);
        }
        ArrayList<Integer> temp = new ArrayList<>();
        for(Integer m : count){
            temp.add(m);
        }
        Collections.sort(temp);
        int sum = 0;
        for(Integer e : temp){
            sum += record.get(e);
            result = Math.max(result , sum);
        }
        return result;
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值