使用 Python 进行公司航班预订
pythonserver side programmingprogramming更新于 2025/11/13 5:00:17
假设我们有 n 个航班,它们被标记为从 1 到 n。我们有一个航班预订列表。第 i 个预订表示使用 bookings[i] = [i, j, k],这意味着我们从标记为 i 到 j 的航班(含)中预订了 k 个座位。找到一个长度为 n 的数组 answer,按标签顺序显示每个航班上预订的座位数。因此,如果输入为 [[1,2,10],[2,3,20],[2,5,25]] 且 n = 5,则输出将为 [10, 55, 45, 25, 25]。
为了解决这个问题,我们将遵循以下步骤 −
- res := 创建一个大小为 n 的数组,并用 0 填充
- 对于 bookings 中的每个条目 i
- res[i[0] - 1] := res[i[0] - 1] + i[2]
- 如果 i[1] < n,则 res[i[1]] := res[i[1]] – i[2]
- 对于范围为 1 到 n 的 i – 1
- res[i] := res[i] + res[i - 1]
- 返回 res
让我们看看下面的实现以便更好地理解 −
示例
class Solution(object): def corpFlightBookings(self, bookings, n): res = [0 for i in range(n)] for i in bookings: res[i[0]-1]+=i[2] if(i[1]<n): res[i[1]]-=i[2] for i in range(1,n): res[i]+=res[i-1] return res ob = Solution() print(ob.corpFlightBookings([[1,2,10],[2,3,20],[2,5,25]],5))
输入
[[1,2,10],[2,3,20],[2,5,25]] 5
输出
[10, 55, 45, 25, 25]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

