版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412946
保存一个slice
type NumArray struct {
nums []int
}
func Constructor(nums []int) NumArray {
nn := []int{}
if len(nums) <= 1 {
nn = nums
} else {
nn = append(nn, nums[0])
for i := 1; i < len(nums); i++ {
nn = append(nn, nums[i]+nn[i-1])
}
}
return NumArray{
nums: nn,
}
}
func (this *NumArray) SumRange(i int, j int) int {
if i == 0 {
return this.nums[j]
} else {
return this.nums[j] - this.nums[i-1]
}
}