zoukankan      html  css  js  c++  java
  • 区间之和

    题目来自:https://leetcode-cn.com/problems/range-addition/

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

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

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

    示例:

    输入: length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]
    输出: [-2,0,3,5,3]

    解释:

    初始状态:
    [0,0,0,0,0]
    
    进行了操作 [1,3,2] 后的状态:
    [0,2,2,2,0]
    
    进行了操作 [2,4,3] 后的状态:
    [0,2,5,5,3]
    
    进行了操作 [0,2,-2] 后的状态:
    [-2,0,3,5,3]

    思路:

    public class P370RangeAddition {
    
        //输入: length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]
        //输出: [-2,0,3,5,3]
        public static void main(String[] args) {
            Solution solution = new P370RangeAddition().new Solution();
            // TO TEST
            int[] arr = solution.getModifiedArray(5, new int[][]{{1, 3, 2}, {2, 4, 3}, {0, 2, -2}});
            for (int i : arr) {
                System.out.print(i + ",");
            }
    
        }
    
        //思路:a[start] = a[start] + value,a[end+1] = a[end+1] - value
        class Solution {
            public int[] getModifiedArray(int length, int[][] updates) {
    
                int[] arr = new int[length];
    
                for (int[] update : updates) {
                    arr[update[0]] += update[2];
                    if (update[1] < length - 1) {
                        arr[update[1] + 1] -= update[2];
                    }
                }
    
                for (int i = 1; i < length; i++) {
                    arr[i] += arr[i - 1];
                }
    
                return arr;
            }
        }
    }

     

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/range-addition

  • 相关阅读:
    Python Revisited Day 13 (正则表达式)
    Python Revisited Day 06 (面向对象程序设计)
    Python Revisited (变量)
    Python Revisited Day 05(模块)
    Python Revisited Day 04 (控制结构与函数)
    Python Revisited Day 03 (组合数据类型)
    Numpy
    Python Revisited Day 01
    Python3使用openpyxl读写Excel文件
    Python3操作YAML文件
  • 原文地址:https://www.cnblogs.com/zhihaospace/p/12604402.html
Copyright © 2011-2022 走看看