Golang Leetcode 307. Range Sum Query - Mutable.go

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

版权声明:原创勿转 https://blog.csdn.net/anakinsun/article/details/89055121

思路

slice里保存的是前n个数的和,方便更新操作

code

type NumArray struct {
	n []int
}

func Constructor(nums []int) NumArray {
	n := []int{}
	if len(nums) <= 1 {
		n = nums
	} else {
		n = append(n, nums[0])
		for i := 1; i < len(nums); i++ {
			n = append(n, nums[i]+n[i-1])
		}
	}
	return NumArray{
		n: n,
	}
}

func (this *NumArray) Update(i int, val int) {
	l := len(this.n)
	if i < 0 || i > l-1 {
		return
	}
	var diff int
	if i == 0 {
		diff = val - this.n[0]
	} else {
		diff = val - (this.n[i] - this.n[i-1])
	}
	for j := i; j < l; j++ {
		this.n[j] += diff
	}
}

func (this *NumArray) SumRange(i int, j int) int {
	if i == 0 {
		return this.n[j]
	} else {
		return this.n[j] - this.n[i-1]
	}
}