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.
Ideas of solving problems
Subtract the sum array.Calculate the sum of the previous I Numbers in advance, that is, a[I] is equal to the sum of the interval [1, I], and the consumption time is O(n).The sum of the interval [I,j] is: sum(I,j) = a[j] -a [I -1], the elapsed time of each query is O(1), and the time complexity of k queries is O(k).So in general, it’s O(n+k). The space complexity is O(n). The time consumption is 8.4Mb.
Code
type NumArray struct {
presum []int // 存储 [0,i] 的和
}
func Constructor(nums []int) NumArray {
a := NumArray{}
a.presum = append(a.presum, 0) // 初始化 presum 数组
for i:=1; i<=len(nums); i++ {
t := a.presum[i-1] + nums[i-1]
a.presum = append(a.presum, t)
}
return a
}
func (this *NumArray) SumRange(i int, j int) int {
return this.presum[j+1] - this.presum[i]
}
/**
* Your NumArray object will be instantiated and called as such:
* obj := Constructor(nums);
* param_1 := obj.SumRange(i,j);
*/
链接:https://leetcode-cn.com/problems/range-sum-query-immutable/solution/48mssan-chong-fang-fa-de-go-shi-xian-by-elliotxx/
来源:力扣(LeetCode)