[LeetCode] Range Sum Query - Immutable

303. Range Sum Query - Immutable

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

  1. 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.
  • 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
class NumArray {
vector<int> prefixSum;
public:
NumArray(vector<int>& nums) {
prefixSum.push_back(0);
for(auto n : nums) {
prefixSum.push_back(n + prefixSum.back());
}
}

int sumRange(int left, int right) {
return prefixSum[right+1] - prefixSum[left];
}
};

/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(left,right);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/08/PS/LeetCode/range-sum-query-immutable/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.