差分数组、前缀和

一、题目 —— Leetcode1109、航班预订统计

在这里插入图片描述

二、思路 —— 差分数组+前缀和

图解
在这里插入图片描述
代码

class Solution {
    public int[] corpFlightBookings(int[][] bookings, int n) {
        // 计算差分数组
        int[] res = new int[n];
        for (int[] booking:bookings) {
            res[booking[0]-1] += booking[2];
            if (booking[1]<n) {
                res[booking[1]] -=booking[2];
            }
        }      
        // 计算前缀和,恢复返回的数组
        for (int i = 1;i<res.length;i++) {
            res[i]+=res[i-1];
        }
        return res;
    }
}

三、题目 —— Leetcode1094、拼车

在这里插入图片描述
提示:
你可以假设乘客会自觉遵守 “先下后上” 的良好素质
trips.length <= 1000
trips[i].length == 3
1 <= trips[i][0] <= 100
0 <= trips[i][1] < trips[i][2] <= 1000
1 <= capacity <= 100000

四、思路 —— 差分数组、前缀和

示例一图解
在这里插入图片描述
代码:

class Solution {
    public boolean carPooling(int[][] trips, int capacity) {
        // 计算拆分数组
        int[] res = new int[1001];
        for(int[] trip:trips) {
            res[trip[1]] += trip[0];
            res[trip[2]] -= trip[0];
        }

        // 统计每一站还剩多少人,大于capacity则返回false
        int total = 0;
        for (int person : res) {
            total += person;
            if (total > capacity) {
                return false;
            }
        }
        return true;
    }
}

总结:

对数组的某一段进行增减操作,通过差分可以在o(n)时间完成。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值