303. Range Sum Query - Immutable
https://leetcode.com/problems/range-sum-query-immutable/
js
/**
* @constructor
* @param {number[]} nums
*/
var NumArray = function(nums) {
var sums = [];
for (var i = 0; i < nums.length; i++) {
sums[i] = i === 0 ? nums[0] : (sums[i - 1] + nums[i]);
}
this.sums = sums;
};
/**
* @param {number} i
* @param {number} j
* @return {number}
*/
NumArray.prototype.sumRange = function(i, j) {
var sums = this.sums;
return i === 0 ? sums[j] : (sums[j] - sums[i - 1]);
};
/**
* Your NumArray object will be instantiated and called as such:
* var numArray = new NumArray(nums);
* numArray.sumRange(0, 1);
* numArray.sumRange(0, 2);
*/
py
class NumArray(object):
def __init__(self, nums):
"""
initialize your data structure here.
:type nums: List[int]
"""
self.sums = []
for i in range(len(nums)):
self.sums.append(nums[i] if i == 0 else self.sums[i - 1] + nums[i])
def sumRange(self, i, j):
"""
sum of elements nums[i..j], inclusive.
:type i: int
:type j: int
:rtype: int
"""
return self.sums[j] if i == 0 else self.sums[j] - self.sums[i - 1]
# Your NumArray object will be instantiated and called as such:
# numArray = NumArray(nums)
# numArray.sumRange(0, 1)
# numArray.sumRange(1, 2)