版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/89055095
思路
保存一个slice
code
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]
}
}
更多内容请移步我的repo: https://github.com/anakin/golang-leetcode