left和right都是从1开始计算的
查分数组方式
class Solution {
public int[] corpFlightBookings(int[][] bookings, int n) {
int[] nums = new int[n];
int[] res = new int[n];
for(int[] row:bookings){
int left = row[0];
int right = row[1];
int value = row[2];
nums[left-1] += value;
//注意超出边界情况
if(right<n){
nums[right] -= value;
}
}
res[0] = nums[0];
for(int i = 1;i<n;i++){
res[i] = res[i-1] + nums[i];
}
return res;
}
}
完整差分数组定义:
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;
}
}