LeetCode 1109. Corporate Flight Bookings

231 篇文章 0 订阅

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 <= bookings.length <= 20000
  • 1 <= bookings[i][0] <= bookings[i][1] <= n <= 20000
  • 1 <= bookings[i][2] <= 10000

-------------------------------------------------------

受到 Merge Intervals 这题的影响,上来先排了个序,对结束条件开始没处理好,还不行bug了一下,代码如下:

class Solution:
    def corpFlightBookings(self, bookings, n):
        lst,res = [(item[0]-1,0,item[2]) for item in bookings]+[(item[1]-1,1,item[2]) for item in bookings],[0 for i in range(n)]
        lst.sort()
        pre,accu=0,0
        for pos,tag,book in lst:
            while(pre<pos):
                res[pre] = accu
                pre += 1
            if (tag == 0):
                accu += book
                res[pre] = accu
            else:
                if (pos == pre): #bug: 开始没有考虑清楚这坑
                    res[pre] = accu
                    pre += 1
                accu -= book
        return res

后来去discussion看,根本不用预先排序,累加之前的结果就好,由于输出形式不同,trick也不一样,慢慢感受一下:

class Solution:
    def corpFlightBookings(self, bookings, n):
        res = [0 for i in range(n+1)]
        for booking in bookings:
            start,end,seat = booking[0]-1,booking[1]-1,booking[2]
            res[start] += seat
            res[end+1] -= seat
        for i in range(1,n):
            res[i] += res[i-1]
        return res[:-1]

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值