[LeetCode] 370. Range Addition

You are given an integer length and an array updates where updates[i] = [startIdxi, endIdxi, inci].

You have an array arr of length length with all zeros, and you have some operation to apply on arr. In the ith operation, you should increment all the elements arr[startIdxi], arr[startIdxi + 1], ..., arr[endIdxi] by inci.

Return arr after applying all the updates.

 

Example 1:

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

Example 2:

Input: length = 10, updates = [[2,4,6],[5,6,8],[1,9,-4]]
Output: [0,-4,2,2,2,4,4,-4,-4,-4]

Constraints:

  • 1 <= length <= 105
  • 0 <= updates.length <= 104
  • 0 <= startIdxi <= endIdxi < length
  • -1000 <= inci <= 1000

区间加法。

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/range-addition
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是前缀和/扫描线,注意这一类题型在有的题解里又被叫做差分数组。题意很简单,但是由于数据范围的关系,暴力解一定是会超时的。累加和的思路是首先我们创建一个长度为 length 的数组记录最后的累加和的结果。当我们拿到 [startIndex, endIndex, inc] 这样的组合的时候,我们在 startIndex 的位置 += inc,在 endIndex + 1 的位置 -= inc。在遍历完所有的 inquiries 之后,我们对整个数组累加一下,就得到最后的结果了。注意在 endIndex + 1 做减法的时候需要特判避免越界问题,因为题目给的 updates 表示的是闭区间。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int[] getModifiedArray(int length, int[][] updates) {
 3         int[] res = new int[length];
 4         for (int[] update : updates) {
 5             int start = update[0];
 6             int end = update[1];
 7             int val = update[2];
 8             res[start] += val;
 9             if (end + 1 < length) {
10                 res[end + 1] -= val;
11             }
12         }
13         
14         for (int i = 1; i < length; i++) {
15             res[i] += res[i - 1];
16         }
17         return res;
18     }
19 }

 

LeetCode 题目总结

posted @ 2021-03-28 12:16  CNoodle  阅读(247)  评论(0编辑  收藏  举报