[LeetCode] 370. Range Addition

370. Range Addition

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
vector<int> getModifiedArray(int length, vector<vector<int>>& updates) {
int add(0);
vector<int> res(length, 0);
priority_queue<pair<int, int>> pq;
sort(begin(updates), end(updates));
auto it = begin(updates);

for(int i = 0; i < length and not (it == end(updates) and pq.empty()); i++) {
while(it != end(updates) && (*it)[0] == i) {
add += (*it)[2];
pq.push({-(*it)[1], -(*it)[2]});
it++;
}
res[i] += add;
while(!pq.empty() && -pq.top().first == i) {
add += pq.top().second;
pq.pop();
}

if(!add and it != end(updates) and pq.empty()) {
i = (*it)[0] - 1;
}

}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/14/PS/LeetCode/range-addition/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.