题目
这里有 n 个航班,它们分别从 1 到 n 进行编号。
有一份航班预订表 bookings ,表中第 i 条预订记录 bookings[i] = [firsti, lasti, seatsi] 意味着在从 firsti 到 lasti (包含 firsti 和 lasti )的 每个航班 上预订了 seatsi 个座位。
请你返回一个长度为 n 的数组 answer,其中 answer[i] 是航班 i 上预订的座位总数。
示例一:
输入:bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
输出:[10,55,45,25,25]
解释:
航班编号 1 2 3 4 5
预订记录 1 : 10 10
预订记录 2 : 20 20
预订记录 3 : 25 25 25 25
总座位数: 10 55 45 25 25
因此,answer = [10,55,45,25,25]
示例二:
输入:bookings = [[1,2,10],[2,2,15]], n = 2
输出:[10,25]
解释:
航班编号 1 2
预订记录 1 : 10 10
预订记录 2 : 15
总座位数: 10 25
因此,answer = [10,25]
解法
暴力
class Solution {
public int[] corpFlightBookings(int[][] bookings, int n) {
int[] res = new int[n];
for(int[] b : bookings) {
for(int i = b[0]-1; i < b[1] ; ++i) {
res[i] += b[2];
}
}
return res;
}
}
差分
每一个bookings小数组都代表一个区间里的增量,所以可以在区间的端点上面表示增量变化,每个区间左端点代表增加,右端点表示减少。
class Solution {
public int[] corpFlightBookings(int[][] bookings, int n) {
int[] temp = new int[n];
int[] res = new int[n];
for(int[] b : bookings) {
int start = b[0]-1;
int end = b[1];
int add = b[2];
temp[start] += add;
if(end < n)
temp[end] -= add;
}
int sum = 0;
for(int i = 0 ; i < n ; ++i) {
sum += temp[i];
res[i] += sum;
}
return res;
}
}