303. 区域和检索 - 数组不可变

区域和检索 - 数组不可变

解法一: 前缀和

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
type NumArray struct {
preSum []int
}

func Constructor(nums []int) NumArray {
sum := 0
preSum := make([]int, len(nums)+1)
for i, num := range nums {
sum += num
preSum[i+1] = sum
}
return NumArray{
preSum,
}
}

func (this *NumArray) SumRange(left int, right int) int {
preSum := this.preSum
return preSum[right+1] - preSum[left]
}

/**
* Your NumArray object will be instantiated and called as such:
* obj := Constructor(nums);
* param_1 := obj.SumRange(left,right);
*/
作者

wuhunyu

发布于

2024-03-18

更新于

2025-01-15

许可协议