303. Range Sum Query - Immutable
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
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
type NumArray struct {
Data []int
sum []int
}
func Constructor(nums []int) NumArray {
d := NumArray{Data: nums}
if len(nums) == 0 {
return d
}
d.sum = make([]int, len(nums))
d.sum[0] = d.Data[0]
for i := 1; i < len(nums); i++ {
d.sum[i] = d.sum[i-1] + nums[i]
}
return d
}
func (this *NumArray) SumRange(i int, j int) int {
return this.sum[j] - this.sum[i] + this.Data[i]
}