[LeetCode] Range Sum Query - Mutable

307. Range Sum Query - Mutable

Given an integer array nums, handle multiple queries of the following types:

  1. Update the value of an element in nums.
  2. Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.

Implement the NumArray class:

  • NumArray(int[] nums) Initializes the object with the integer array nums.
  • void update(int index, int val) Updates the value of nums[index] to be val.
  • int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + … + nums[right]).
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class NumArray {
vector<int> acc;
vector<int> nums;
map<int, int> updated;
void updateAcc(int from) {
for(int i = from; i < nums.size(); i++) {
acc[i + 1] = acc[i] + nums[i];
}
}
void updateNums() {
int minimumUpdate = updated.lower_bound(-1)->first;
for(auto& entity : updated) {
nums[entity.first] = entity.second;
}
updateAcc(minimumUpdate);
updated.clear();
}
public:
NumArray(vector<int>& nums) : nums(nums){
acc.reserve(nums.size() + 1);
acc[0] = 0;
updateAcc(0);
}

void update(int index, int val) {
updated[index] = val;
if(updated.size() >= 100) {
updateNums();
}
}

int sumRange(int left, int right) {
int res = acc[right + 1] - acc[left];
for(auto it = updated.lower_bound(left); it != end(updated) && it->first <= right; it++) {
res = res - nums[it->first] + updated[it->first];
}
return res;
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* obj->update(index,val);
* int param_2 = obj->sumRange(left,right);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/28/PS/LeetCode/range-sum-query-mutable/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.