LintCode Number of Airplanes in the Sky(Java)

题目如下:

Given an interval list which are flying and landing time of the flight. How many airplanes are on the sky at most?
Have you met this question in a real interview? Yes
Example
For interval list [[1,10],[2,3],[5,8],[4,7]], return 3
Note
If landing and flying happens at the same time, we consider landing should happen at first.


分析如下:

见到网上一些基于interval排序的做法,我觉得这道题还可以用HashMap来做,这样空间换时间,降低了时间复杂度。

首先,每个x对应HashMap的key, 比如在Interval (1, 5)这段有飞机飞过,那么说明在时间点为(1, 2, 3, 4, 5)的时候,各有一架飞机在空中,也就是说HashMap中可以存入(key, value)分别为(1, 1,), (2, 1,), (3, 1,), (4, 1,), (5, 1,)的 (key, value) pair。

其次,注意到题目说的,If landing and flying happens at the same time, we consider landing should happen at first.也就是说,interval(1, 5)这段和interval (5, 9)这段如果都有飞机飞过,在5这个点上,依然只能算作只有个一个飞机飞过。所以上面的(key, value) pari要修正一下。之前是把[interva.start, interval.end]的左闭右闭区间中的所有点放入HashMap,现在考虑到landing这个条件,应该只把[interva.start, interval.end)的左闭右开区间的所有点放入HashMap.


我的代码:

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 max = 0;
        HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
        if (airplanes == null || airplanes.size() == 0) {
            return 0;
        }
        for (Interval interval: airplanes) {
            for (int i = interval.start; i < interval.end; ++i) {
                if (hashMap.containsKey(i)) {
                    hashMap.put(i, hashMap.get(i) + 1);
                } else {
                    hashMap.put(i, 1);
                }
                max = Math.max(hashMap.get(i), max);
            }
        }
        return max;
    }
}


补充说明:

网上搜到一些基于排序的做法也挺容易懂的,比如这里 https://codesolutiony.wordpress.com/2015/05/12/lintcode-number-of-airplanes-in-the-sky/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值