差分数组
差分数组的适用场景是:频繁对原始数组的某个区间的元素进⾏增减。
//第一步:构建差分数组 func Diff(nums []int)[]int{ m:=len(nums) if m==0{ return []int{} } diff:=make([]int,m) diff[0]=nums[0] for i:=1;i<m;i++{ diff[i]=nums[i]-nums[i-1] } return diff } //第二步:给闭区间[i,j]增加val func Increment(diff []int,i ,j, val int){ diff[i]+=val if j+1<len(diff){ diff[j+1]-=val } } //第三步:返回结果数组 func Result(diff []int)[]int{ if len(diff)==0{ return []int{} } res:=make([]int,len(diff)) res[0]=diff[0] for i:=1;i<len(diff);i++{ res[i]=res[i-1]+diff[i] } return res }