[leetcode] 1109. Corporate Flight Bookings

Description

There are n flights, and they are labeled from 1 to n.

We have a list of flight bookings. The i-th booking bookings[i] = [i, j, k] means that we booked k seats from flights labeled i to j inclusive.

Return an array answer of length n, representing the number of seats booked on each flight in order of their label.

Example 1:

Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
Output: [10,55,45,25,25]

Constraints:

  1. 1 <= bookings.length <= 20000.
  2. 1 <= bookings[i][0] <= bookings[i][1] <= n <= 20000.
  3. 1 <= bookings[i][2] <= 10000

分析

题目的意思是:给定一个bookings的数组,数组中每个元素包含三个值,i,j,k,表示从第i到第j包含k个座位,现在按照顺序输出每个位置的座位数目。这道题我一开始用了暴力破解,果然超时了,最后参考了一下别人的代码,发现用一个求和数组就可以,我不太明白第一个循环是什么意思,但是我验证过了,却是最后求和得到的是正确的结果,对于例1,这里我把第一个循环得到的res输出输出来:

[10,20+25,-10,-20,0,-25]

然后按照第二个循环求和就能得到答案,我晕了。

代码

class Solution:
    def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
        res=[0]*(n+1)
        for i,j,k in bookings:
            res[i-1]+=k
            res[j]-=k
        res.pop()
        for i in range(1,n):
            res[i]+=res[i-1]
        return res        

参考文献

[LeetCode] Python O(n) solution | Top 98% Speed | 9 Lines of Code

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值