-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
72 lines (58 loc) · 1.3 KB
/
main.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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import "fmt"
// Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
//
// Example:
// Given nums = [-2, 0, 3, -5, 2, -1]
//
// sumRange(0, 2) -> 1
// sumRange(2, 5) -> -1
// sumRange(0, 5) -> -3
// Note:
// You may assume that the array does not change.
// There are many calls to sumRange function.
type NumArray struct {
sum map[int]int
}
func Constructor(nums []int) NumArray {
sum := make(map[int]int)
var s int
for i, n := range nums {
s += n
sum[i] = s
}
return NumArray{sum: sum}
}
func (this *NumArray) SumRange(i int, j int) int {
return this.sum[j] - this.sum[i-1]
}
/**
* Your NumArray object will be instantiated and called as such:
* obj := Constructor(nums);
* param_1 := obj.SumRange(i,j);
*/
// slice is better
/*
type NumArray struct {
sums []int
}
func Constructor(nums []int) NumArray {
this := NumArray{}
this.sums = make([]int, len(nums)+1)
s := 0
for i := 0; i < len(nums); i++ {
s += nums[i]
this.sums[i+1] = s
}
return this
}
func (this *NumArray) SumRange(i int, j int) int {
return this.sums[j+1] - this.sums[i]
}
*/
func main() {
num := Constructor([]int{-2, 0, 3, -5, 2, -1})
fmt.Println(num.SumRange(0, 2))
fmt.Println(num.SumRange(2, 5))
fmt.Println(num.SumRange(0, 5))
}