Golang Leetcode 303. Range Sum Query - Immutable.go

2019-04-12 13:56:19 浏览数 (1)

版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412946

思路

保存一个slice

code

代码语言:javascript复制
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]
	}
}

0 人点赞