391.Number of Airplanes in the Sky-数飞机(中等题)
来源:互联网 发布:国家打击网络暴恐信息 编辑:程序博客网 时间:2024/06/07 08:33
数飞机
题目
给出飞机的起飞和降落时间的列表,用 interval 序列表示. 请计算出天上同时最多有多少架飞机?
注意事项
如果多架飞机降落和起飞在同一时刻,我们认为降落有优先权。样例
对于每架飞机的起降时间列表:[[1,10],[2,3],[5,8],[4,7]], 返回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
- 391.Number of Airplanes in the Sky-数飞机(中等题)
- LintCode --number-of-airplanes-in-the-sky(数飞机)
- lintcode:Number of Airplanes in the Sky
- lintcdoe: Number of Airplanes in the Sky
- [LintCode]Number of Airplanes in the Sky
- LintCode Number of Airplanes in the Sky(Java)
- [lintcode] - 391 Number of Airplanes in the Sky
- 196.Find the Missing Number-寻找缺失的数(中等题)
- 248.Count of Smaller Number-插入区间(中等题)
- 4.Ugly Number II-丑数 II(中等题)
- 184.Largest Number-最大数(中等题)
- 205.Interval Minimum Number-区间最小数(中等题)
- 518.Super Ugly Number-超级丑数(中等题)
- PIE IN THE SKY
- The Scar of the Sky
- 425.Letter Combinations of a Phone Number-电话号码的字母组合(中等题)
- 83.Single Number II-落单的数 II(中等题)
- 84.Single Number III-落单的数 III(中等题)
- uml——活动图和状态图
- 操作元素的CSS样式、正则表达式、心得
- JSP JavaBeans
- 在sqlplus中使用退格和上下左右
- POJ3190
- 391.Number of Airplanes in the Sky-数飞机(中等题)
- 机器学习算法--逻辑回归原理介绍
- Java SE基础知识
- MapReduce_TotalSort示例
- Url与Uri与URN的区别:
- 11.12
- Python time模块简介
- 学习安卓相关的网站
- Struts2 的jar包冲突如何解决?