创建diff数组来存储数据的变化值,
即diff[i] = nums[i] - nums[i-1];
diff[i] = diff[i]+val;
diff[j+1] = diff[j+1] - val;
结果res再由
res[i] = res[i-1]+diff[i];
得到
class Solution {
public int[] corpFlightBookings(int[][] bookings, int n) {
int[] nums = new int[n];
Different df = new Different(nums);
for(int[] update :bookings){
int i = update[0]-1;
int j = update[1]-1;
int val = update[2];
df.increment(i,j,val);
}
return df.result();
}
}
class Different{
private int[] diff;
public Different(int[] nums){
assert nums.length > 0;
diff = new int[nums.length];
diff[0] = nums[0];
for(int i= 1;i<diff.length;i++){
diff[i] = nums[i] - nums[i-1];
}
}
public void increment(int i,int j, int val){
diff[i] = diff[i]+val;
if(j+1<diff.length){
diff[j+1] = 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;
}
}