1109. 航班预订统计(Java、差分数组)

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;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值