这是 LeetCode 上2021-8-31的每日一题:「1109. 航班预订统计」
1. 题目描述
这里有n
个航班,它们分别从1
到n
进行编号。
有一份航班预订表bookings
,表中第i
条预订记录bookings[i] = [firsti, lasti, seatsi]
意味着在从firsti
到lasti
(包含firsti
和lasti
)的每个航班上预订了seatsi
个座位。
请你返回一个长度为n
的数组answer
,其中answer[i]
是航班i
上预订的座位总数。
示例 1:
输入:bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
输出:[10,55,45,25,25]
解释:
航班编号 1 2 3 4 5
预订记录 1 : 10 10
预订记录 2 : 20 20
预订记录 3 : 25 25 25 25
总座位数: 10 55 45 25 25
因此,answer = [10,55,45,25,25]
示例 2:
输入:bookings = [[1,2,10],[2,2,15]], n = 2
输出:[10,25]
解释:
航班编号 1 2
预订记录 1 : 10 10
预订记录 2 : 15
总座位数: 10 25
因此,answer = [10,25]
2. 解答
- 预定表中的每一条记录是一个区间,表示区间内的值都有某个数
- 定义返回的数组
nums
- 遍历预定表,取出每个记录的起点、终点、数量
- 因为起点是从1开始的,所以
nums
在start - 1
处多num
,在end
处少num
- 最后对
nums
求前缀和,就可以把每个站点的数量表示出来了
const corpFlightBookings = (bookings, n) => {
const nums = new Array(n).fill(0);
for (const booking of bookings) {
// 取出起点、终点、数量
const [start, end, num] = booking;
// 因为起点从1开始,所以登机的数量在start - 1处多num
nums[start - 1] += num;
// 如果还没到终点站,在end处有num人下机
if (end < n) nums[end] -= num;
}
// 求前缀和
for (let i = 1; i < n; i++) {
nums[i] += nums[i - 1];
}
return nums;
};
😄最近新创建了个开源仓库,总结LeetCode的每日一题,目前已有C++、JavaScript语言版本,欢迎大家提供其他语言版本!
🖥️仓库地址:「每日一题系列」