[leetcode] 370. Range Addition 解题报告

这篇博客介绍了LeetCode上的370题,即Range Addition问题。作者提供了问题的背景、示例解释以及解题思路。思路提到,不需要每次更新整个区间,只需更新起点和终点后的值,通过累加和得到最终结果。文章包含具体的解题代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接: https://leetcode.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.

Example:

Given:

    length = 5,
    updates = [
        [1,  3,  2],
        [2,  4,  3],
        [0,  2, -2]
    ]

Output:

    [-2, 0, 3, 5, 3]

Explanation:

Initial state:
[ 0, 0, 0, 0, 0 ]

After applying operation [1, 3, 2]:
[ 0, 2, 2, 2, 0 ]

After applying operation [2, 4, 3]:
[ 0, 2, 5, 5, 3 ]

After applying operation [0, 2, -2]:
[-2, 0, 3, 5, 3 ]

思路: 隐约记得这题好像是在13年南理工ACM比赛的一题, 当时感觉应该像是线段树, 不过没做出来. 当时太水了, 现在依然很水!

在这题中没必要每次把区间的每一个值都更新, 只需要更新起点和终点后的一点即可. 也就是说把增加的值放在起点, 终点后的一点减去增加的值, 这样再扫描的时候把之前累加的和作为最终值即可. 

代码如下:

class Solution {
public:
    vector<int> getModifiedArray(int length, vector<vector<int>>& updates) {
        vector<int> ans(length, 0);
        for(auto vec1: updates)
        {
            int left = vec1[0], right = vec1[1], val = vec1[2];
            ans[left] += val;
            if(right+1 < length) ans[right+1] -= val;
        }
        for(int i = 0, sum = 0; i < length; i++)
        {
            sum += ans[i];
            ans[i] = sum;
        }
        return ans;
    }
};
参考: https://discuss.leetcode.com/topic/49691/java-o-k-n-time-complexity-solution

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值