zoukankan      html  css  js  c++  java
  • [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 的位置 -= 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 题目总结

  • 相关阅读:
    C# 开发(创蓝253)手机短信验证码接口
    33条C#、.Net经典面试题目及答案
    请用一句sql语句取出各科的平均成绩,显示字段,科目,平均成绩
    写出一条Sql语句:取出表A中第31到第40记录(SQLServer,以自动增长的ID作为主键,注意:ID可能不是连续的。
    SQL的四种连接-左外连接、右外连接、内连接、全连接
    C# 获取mp3文件的歌曲时间长度
    欧拉公式
    linux环境java入门
    C内存分配
    机器学习网址归纳
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14588231.html
Copyright © 2011-2022 走看看