
Leetcode Problem 303: Range Sum Query - Immutable
Design a NumArray class that preprocesses an integer array nums at construction time to efficiently answer multiple range sum queries. Each query sumRange(left, right) returns the sum of elements from index left to right inclusive.
NumArray(nums) — Initializes the object with the integer array.sumRange(left, right) — Returns the sum of nums[left] through nums[right] inclusive.Constraints:
0 <= left <= right < nums.length.class NumArray {
private prefixSum: number[]
constructor(nums: number[]) {
let sum = 0;
this.prefixSum = nums.map(num => sum += num);
console.log(this.prefixSum)
}
sumRange(left: number, right: number): number {
if (left === 0) {
return this.prefixSum[right]
}
return this.prefixSum[right] - this.prefixSum[left - 1]
}
}
/**
* Your NumArray object will be instantiated and called as such:
* var obj = new NumArray(nums)
* var param_1 = obj.sumRange(left,right)
*/