0%

range-sum-query-immutable

Range Sum Query - Immutable – LeetCode 303

Problem

Description

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class NumArray {
private:
vector<int> map{0};
public:
NumArray(vector<int> nums) {
for(int i = 0, acc = 0; i != nums.size(); ++i){
acc += nums[i];
map.push_back(acc);
}
}

int sumRange(int i, int j) {
return map[j+1] - map[i];
}
};

/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/

思路

因为不可变所以建立一个缓存,用空间换时间,对于map[n] = num[1] + … + num[n],然后自然可得sumRange(i,j) = map[j] - map[i]。时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$163$ ms,排名$16.83\%$

Better

思路

还没看到更好的思路。