391.Number of Airplanes in the Sky-数飞机(中等题)

本文介绍了一种算法,用于计算给定飞机起降时间列表中天空中同时存在的最多飞机数量。通过遍历起降时间并使用HashMap记录每个时刻的增减情况,再通过排序和累加找出最大值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数飞机

  1. 题目

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

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

  2. 样例

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

  3. 题解

    对起降时间列表进行遍历,用HashMap记录每个start和end的数量,start加1,end减1。然后对HashMap按照key排序(这里使用的是桶排序,也可以使用Collections.sort),再对valueSet进行遍历累加,找到这个累加值的峰值就是答案。
    如样例所示,对时刻表遍历后得到:
    k  1  10 2  3  5 8 4  7
    v  1 -1   1 -1 1 1 1 -1
    排序后为:
    k  1 2  3 4 5   7  8  10
    v  1 1 -1 1 1 -1 -1 -1
    再对valueSet进行遍历累加k=5时最大值为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) { 
        if (airplanes.size() == 0)
        {
            return 0;
        }
        HashMap<Integer,Integer> map = new HashMap<>();
        int min = Integer.MAX_VALUE;
        int max = 0;
        for (int i=0;i<airplanes.size();i++)
        {
            int k = airplanes.get(i).start;
            int v = map.containsKey(airplanes.get(i).start)?map.get(k):0;
            map.put(k,v+1);
            k = airplanes.get(i).end;
            v = map.containsKey(airplanes.get(i).end)?map.get(k):0;
            map.put(k,v-1);
            min = Math.min(min,airplanes.get(i).start);
            max = Math.max(max,airplanes.get(i).end);
        }
        int[] nums = new int[max-min+1];
        for (Integer k : map.keySet())
        {
            int v = map.get(k);
            nums[k-min] = v;
        }
        int result = 0;
        int count = 0;
        for (int i=0;i<nums.length;i++)
        {
            count += nums[i];
            result = Math.max(result,count);
        }
        return result;
    }
}

Last Update 2016.11.13

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值