Leetcode-1109. Corporate Flight Bookings

本文探讨了LeetCode上的航班预订问题,通过直观方法和累积求和策略对比,展现了算法优化的重要性。初始方法虽直接但效率低下,受时间限制影响。优化后的累积求和策略大幅提升了算法效率,实现O(booking+N)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Original link: https://leetcode.com/problems/corporate-flight-bookings/

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

Intuitive method:
Initialize an array whose length is equal to n.
For each record, do increments to each elements.

Code:

class Solution(object):
    def corpFlightBookings(self, bookings, n):
        """
        :type bookings: List[List[int]]
        :type n: int
        :rtype: List[int]
        """
        op = [0 for i in range(n)]
        
        d = dict()
        
        for i in bookings:
            tag = str(i[0]) + "-" + str(i[1])
            
            if tag in d:
                d[tag] += i[2]
            else:
                d[tag] = i[2]
                
        
        for i in d:
            
            intervals = i.split("-")
            for t in range(int(intervals[0])-1, int(intervals[1])):
                op[t] += d[i]
        
        return op

This code runs in O(ML) where M is the number of records and L is the average length of each record.
This code failed when submitted because of Time Limit Exceeded.

https://leetcode.com/problems/corporate-flight-bookings/discuss/328856/JavaC%2B%2BPython-Straight-Forward-Solution

Inspired by the above link, the cumulative sum seems to help.
When the code contains lots of “same” array operations, cumulative sum might help.

Code:

class Solution(object):
    def corpFlightBookings(self, bookings, n):
        """
        :type bookings: List[List[int]]
        :type n: int
        :rtype: List[int]
        """

        op = [0 for i in range(n+1)]
        
        for lo, hi, num in bookings:
            
            op[lo-1] += num
            op[hi] -= num
            
        for i in range(n-1):
            op[i+1] += op[i]
            
        return op[:-1]

The new version runs in O(booking + N) time and O(N) space.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值