​LeetCode刷题实战370:区间加法

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 区间加法,我们先来看题面:

https://leetcode-cn.com/problems/range-addition/

Assume you have an array of length n initialized with all 0's and are given k update operations.

Each operation is represented as a triplet: [startIndex, endIndex, inc] which increments each element of subarray A[startIndex ... endIndex] (startIndex and endIndex inclusive) with inc.

Return the modified array after all k operations were executed.

假设你有一个长度为 n 的数组,初始情况下所有的数字均为 0,你将会被给出 k 个更新的操作。

其中,每个操作会被表示为一个三元组:[startIndex, endIndex, inc],你需要将子数组 A[startIndex ... endIndex](包括 startIndex 和 endIndex)增加 inc。

请你返回 k 次操作后的数组。

示例

示例:

输入: length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]
输出: [-2,0,3,5,3]

解释:

初始状态:
[0,0,0,0,0]

进行了操作 [1,3,2] 后的状态:
[0,2,2,2,0]

进行了操作 [2,4,3] 后的状态:
[0,2,5,5,3]

进行了操作 [0,2,-2] 后的状态:
[-2,0,3,5,3]

解题

创建一个 int[] 数组 ans,长度为 length。

  对于每一个给定的 [startIndex, endIndex, inc] 我们可以理解成如下:

  把 ans 的 [startIndex,length-1] 都加上了 inc,然后再把 [endIndex+1, length-1] 再减去 inc。

  具体的操作是:

  1、先 ans[startIndex] += val,ans[endIndex+1] += -val;

  2、然后 [startIndex,length-1] 遍历进行 ans[i] += ans[i-1]。

  这样做的目的是因为所有的三元组 [startIndex, endIndex, inc] 对数组 ans 的操作是独立的,我们先对所有的三元组对 ans 的操作在边界上做好,然后遍历一遍 ans 数组即可同时执行完所有三元组对 ans 的操作。

class Solution {
   public int[] getModifiedArray(int length, int[][] updates) {
        int[] ans = new int[length];
        int start, end, val;
        for (int[] update : updates) {
            start = update[0];
            end = update[1];
            val = update[2];
            ans[start] += val;
            if (end < length - 1) {
                ans[end + 1] -= val;
            }
        }
        for (int i = 1; i < length; i++) {
            ans[i] += ans[i - 1];
        }
        return ans;
    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-360题汇总,希望对你有点帮助!

LeetCode刷题实战361:轰炸敌人

LeetCode刷题实战362:敲击计数器

LeetCode刷题实战363:矩形区域不超过 K 的最大数值和

LeetCode刷题实战364:加权嵌套序列和 II

LeetCode刷题实战365:水壶问题

LeetCode刷题实战366:寻找二叉树的叶子节点

LeetCode刷题实战367:有效的完全平方数

LeetCode刷题实战368:最大整除子集数

LeetCode刷题实战369:给单链表加一

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小猿666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值