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 题目总结

  • 相关阅读:
    原生js实现分页功能
    webpack4 前端框架基础配置实例-解决css分离图片路径问题
    Vue cli2.0 项目中使用Monaco Editor编辑器
    Vue相关开源项目库汇总
    git常用配置
    Python 2 下载与安装
    sqlmap下载与安装
    IDEA中集成gitee插件
    双系统之删除Ubuntu系统
    IntelliJ IDEA安装注册教程
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14588231.html
Copyright © 2011-2022 走看看