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

来源:互联网 发布:国家打击网络暴恐信息 编辑:程序博客网 时间:2024/06/07 08:33

数飞机

  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

0 0