1109. Corporate Flight Bookings

本文介绍了一种高效处理航班预订统计的算法。通过将预订区间转化为关键点上的数值变化,使用扫描线(runningsum)技术,可以快速计算出每个航班的具体预订座位数。这种方法避免了直接遍历每个预订区间,大大提高了计算效率。

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

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

running sum,也叫扫描线,重点在于一个interval有一个值的情况下,我们只看变化的index和变化值,最后叠加就是最终答案。

Intuition
Since ranges are continuous, what if we add reservations to the first flight in the range, and remove them after the last flight in range? We can then use the running sum to update reservations for all flights.

This picture shows the logic for this test case: [[1,2,10],[2,3,20],[3,5,25]].
在这里插入图片描述

public int[] corpFlightBookings(int[][] bookings, int n) {
  int[] res = new int[n];
  for (int[] v : bookings) {
    res[v[0] - 1] += v[2];
    if (v[1] < n) res[v[1]] -= v[2];
  }
  for (int i = 1; i < n; ++i) res[i] += res[i - 1];
  return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值