LeetCode: 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.
解题思路 —— 前缀和
记录下前缀和, 即,PrefixSum[i]
表示前 i
个数字的和。
特别地,当 i = 0
时, PrefixSum[i] = 0
。
则 sumRange(i, j) = PrefixSum[j] - PrefixSum[i]
.
AC 代码
type NumArray struct {
PrefixSum []int // 前缀和
}
func Constructor(nums []int) NumArray {
arr := NumArray{ []int{0} }
for i := 0; i < len(nums); i++{
arr.PrefixSum = append(arr.PrefixSum, nums[i] + arr.PrefixSum[i])
}
return arr
}
func (this *NumArray) SumRange(i int, j int) int {
return this.PrefixSum[j+1] - this.PrefixSum[i]
}
/**
* Your NumArray object will be instantiated and called as such:
* obj := Constructor(nums);
* param_1 := obj.SumRange(i,j);
*/