Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 96b69a7

Browse files
committed
Add: Range Sum Query - Immutable
1 parent 6fbcedc commit 96b69a7

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,25 @@
11
package range_sum_query_immutable
2+
3+
type NumArray struct {
4+
sum []int
5+
}
6+
7+
func Constructor(nums []int) NumArray {
8+
sum, na := 0, NumArray{make([]int, len(nums)+1)}
9+
na.sum[0] = 0
10+
for i, v := range nums {
11+
sum += v
12+
na.sum[i+1] = sum
13+
}
14+
return na
15+
}
16+
17+
func (this *NumArray) SumRange(i int, j int) int {
18+
return this.sum[j+1] - this.sum[i]
19+
}
20+
21+
/**
22+
* Your NumArray object will be instantiated and called as such:
23+
* obj := Constructor(nums);
24+
* param_1 := obj.SumRange(i,j);
25+
*/
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,37 @@
11
package range_sum_query_immutable
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
i int
7+
j int
8+
expected int
9+
}
10+
11+
func TestConstructor(t *testing.T) {
12+
nums := []int{-2, 0, 3, -5, 2, -1}
13+
obj := Constructor(nums)
14+
tests := [...]caseType{
15+
{
16+
i: 0,
17+
j: 2,
18+
expected: 1,
19+
},
20+
{
21+
i: 2,
22+
j: 5,
23+
expected: -1,
24+
},
25+
{
26+
i: 0,
27+
j: 5,
28+
expected: -3,
29+
},
30+
}
31+
for _, tc := range tests {
32+
output := obj.SumRange(tc.i, tc.j)
33+
if output != tc.expected {
34+
t.Fatalf("input: %v %v, output: %v, expected: %v", tc.i, tc.j, output, tc.expected)
35+
}
36+
}
37+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /