MrainW's Home

All things come to those who wait!

0%

LeetCode 370. Range Addition

Question

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.

https://leetcode.com/problems/range-addition/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int[] getModifiedArray(int length, int[][] updates) {
int[] res = new int[length];
for (int[] update : updates){
int value = update[2];
int start = update[0];
int end = update[1];
res[start] += value;
if (end < length - 1) res[end + 1] -= value;
}
int sum = 0;
for (int i = 0; i < length; i++){
sum += res[i];
res[i] = sum;
}
return res;
}
}

Complexity:

Time complexity: O( n)

Space complexity: O(n)

Welcome to my other publishing channels