首页 > 其他 > 详细

[LeetCode] 370. Range Addition

时间:2021-03-28 17:53:27      阅读:19      评论:0      收藏:0      [点我收藏+]

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 的位置 -= inc。在遍历完所有的inquiries之后,我们对整个数组累加一下,就得到最后的结果了。

时间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 value = update[2];
 8             res[start] += value;
 9             if (end + 1 < length) {
10                 res[end + 1] -= value;
11             }
12         }
13         for (int i = 1; i < length; i++) {
14             res[i] += res[i - 1];
15         }
16         return res;
17     }
18 }

 

LeetCode 题目总结

[LeetCode] 370. Range Addition

原文:https://www.cnblogs.com/cnoodle/p/14588231.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!