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 }

 

posted @ 2017-03-07 02:46  CodesKiller  阅读(139)  评论(0编辑  收藏  举报