友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

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 ]

Hint:

  • Thinking of using advanced data structures? You are thinking it too complicated.

  • For each update operation, do you really need to update all elements between i and j?

  • Update only the first and end element is sufficient.

  • The optimal time complexity is O(k + n) and uses O(1) extra space.

思路分析

差分数组:把变量记录在差分数组上进行打标,全部打标完成后,再从第二项开始逐项求与前一项的累加值。

0370 01
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public int[] getModifiedArray(int length, int[][] updates) {
  if (updates == null || updates.length == 0) {
    return new int[length];
  }
  int[] diff = new int[length];

  for (int[] update : updates) {
    int start = update[0];
    int end = update[1];
    int val = update[2];
    diff[start] += val;
    if (end + 1 < diff.length) {
      diff[end + 1] -= val;
    }
  }

  for (int i = 1; i < length; i++) {
    diff[i] += diff[i - 1];
  }
  return diff;
}