Golang Leetcode 303. Range Sum Query - Immutable.go

时间:2022-06-19
本文章向大家介绍Golang Leetcode 303. Range Sum Query - Immutable.go,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

版权声明:原创勿转 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]
	}
}