数飞机
本文最后更新于:2024年3月18日 凌晨
数飞机
问题描述
- 给出飞机的起飞和降落时间的列表,用序列
interval
表示。请计算出天上同时最多有多少架飞机?
- 如果多架飞机降落和起飞在同一时刻,我们认为降落有优先权。
样例
1 2 3 4 5 6 7 8
| 输入: [, , , ] 输出: 3 解释: 第一架飞机在1时刻起飞, 10时刻降落。 第二架飞机在2时刻起飞, 3时刻降落。 第三架飞机在5时刻起飞, 8时刻降落。 第四架飞机在4时刻起飞, 7时刻降落。 在5时刻到6时刻之间,天空中有三架飞机。
|
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| public class Solution {
public static void main(String[] args) { System.out.println(new Solution().countOfAirplanes(new int[][]{{1, 10}, {2, 3}, {5, 8}, {4, 7}})); }
public int countOfAirplanes(int[][] interval) { List<AirplanesRecord> recordList = new ArrayList<>(); for (int i = 0; i < interval.length; i++) { recordList.add(new AirplanesRecord(interval[i][0], 1)); recordList.add(new AirplanesRecord(interval[i][1], -1)); } Collections.sort(recordList); int ans = 0; int curr = 0; for (AirplanesRecord record : recordList) { curr += record.countChange; ans = Math.max(ans, curr); } return ans; }
}
class AirplanesRecord implements Comparable<AirplanesRecord> {
int time; int countChange;
AirplanesRecord(int time, int cost) { this.time = time; this.countChange = cost; }
@Override public int compareTo(AirplanesRecord o) { if (time != o.time) { return time - o.time; } return countChange - o.countChange; } }
|