zoukankan      html  css  js  c++  java
  • 370. Range Addition

    Assume you have an array of length n initialized with all 0's and are given k update operations.

    Each operation is represented as a triplet: [startIndex, endIndex, inc] which increments each element of subarray A[startIndex ... endIndex](startIndex and endIndex inclusive) with inc.

    Return the modified array after all k operations were executed.

    Example:

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

    Explanation:

    Initial state:
    [ 0, 0, 0, 0, 0 ]
    
    After applying operation [1, 3, 2]:
    [ 0, 2, 2, 2, 0 ]
    
    After applying operation [2, 4, 3]:
    [ 0, 2, 5, 5, 3 ]
    
    After applying operation [0, 2, -2]:
    [-2, 0, 3, 5, 3 ]

    此题比较有意思,做法也是,每次只要把value值赋值给start,-value值赋值给end+1(如果end<nums.length-1),最后一次遍历和就可以,代码如下:
     1 public class Solution {
     2     public int[] getModifiedArray(int length, int[][] updates) {
     3         int[] nums = new int[length];
     4         for(int[] update:updates){
     5             int start = update[0];
     6             int end = update[1];
     7             int value = update[2];
     8             nums[start] +=value;
     9             if(end<length-1){
    10                 nums[end+1] -= value;
    11             }
    12         }
    13         int sum = 0;
    14         for(int i=0;i<nums.length;i++){
    15             sum+=nums[i];
    16             nums[i] = sum;
    17         }
    18         return nums;
    19     }
    20 }
  • 相关阅读:
    Java 编程规范
    Java常考面试题
    SQL 实战
    快速排序
    剑指Offer(51-67)
    剑指Offer(41-50)
    移动端图片编辑器
    css隐藏和显示table的第一列
    sweetAlert1 设置弹窗宽度,及使用自定义样式
    js获取yyyy-mm-dd hh:mm:ss格式的当前系统时间
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6512834.html
Copyright © 2011-2022 走看看