题目链接
https://leetcode-cn.com/problems/corporate-flight-bookings/
描述
这里有 n 个航班,它们分别从 1 到 n 进行编号。
我们这儿有一份航班预订表,表中第 i 条预订记录 bookings[i] = [j, k, l] 意味着我们在从 j 到 k 的每个
航班上预订了 l 个座位。
请你返回一个长度为 n 的数组 answer,按航班编号顺序返回每个航班上预订的座位数。
提示:
1 <= bookings.length <= 20000
1 <= bookings[i][0] <= bookings[i][1] <= n <= 20000
1 <= bookings[i][2] <= 10000
示例
输入:bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
输出:[10,55,45,25,25]
初始代码模板
class Solution {
public int[] corpFlightBookings(int[][] bookings, int n) {
}
}
代码
很经典的一道差分题目,注意下标即可。
不要使用for遍历,效率太低了,差分技巧可以查看下面这篇介绍:
https://labuladong.gitbook.io/algo/suan-fa-si-wei-xi-lie/3.3-qi-ta-suan-fa-pian/cha-fen-ji-qiao
class Solution {
public int[] corpFlightBookings(int[][] bookings, int n) {
int[] res = new int[n];
int[] diff = new int[n];
for (int[] cur : bookings) {
diff[cur[0] - 1] += cur[2];
if (cur[1] < n) {
diff[cur[1]] -= cur[2];
}
}
res[0] = diff[0];
for (int i = 1; i < n; i++) {
res[i] = res[i - 1] + diff[i];
}
return res;
}
}