难度:medium
思路:
差分数组,注意细节
diff[0] = nums[0];
代码:
class Solution {
public int[] corpFlightBookings(int[][] bookings, int n) {
int[] nums = new int[n];
Difference difference = new Difference(nums);
for (int[] booking: bookings) {
difference.increment(booking[0] - 1, booking[1] - 1, booking[2]);
}
return difference.result();
}
}
// 差分数组工具类
class Difference {
// 差分数组
private int[] diff;
// 根据初始数组nums对差分数组diff进行初始化
public Difference(int[] nums) {
assert nums.length > 0;
diff = new int[nums.length];
diff[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
diff[i] = nums[i] - nums[i - 1];
}
}
// 给闭区间[i, j] 增加 val
public void increment(int i, int j, int val) {
diff[i] += val;
if (j + 1 < diff.length) {
diff[j + 1] -= val;
}
}
// 返回结果数组
public int[] result() {
int[] res = new int[diff.length];
res[0] = diff[0];
for (int i = 1; i <diff.length; i++) {
res[i] = res[i - 1] + diff[i];
}
return res;
}
}
精简版:
class Solution {
public int[] corpFlightBookings(int[][] bookings, int n) {
int[] nums = new int[n];
for (int[] booking : bookings) {
nums[booking[0] - 1] += booking[2];
if (booking[1] < n) {
nums[booking[1]] -= booking[2];
}
}
for (int i = 1; i < n; i++) {
nums[i] += nums[i - 1];
}
return nums;
}
}