未分類

Range Sum Query - Immutable

Range Sum Query - Immutable

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

For Example:

1
2
3
4
5
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.
提示 解題應用
DynamicProgramming 物件概念

Default:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
type NumArray struct {
}
func Constructor(nums []int) NumArray {
}
func (this *NumArray) SumRange(i int, j int) int {
}
/**
* Your NumArray object will be instantiated and called as such:
* obj := Constructor(nums);
* param_1 := obj.SumRange(i,j);
*/

解答思路:

這題沒有什麼技巧,單純測試最基本的物件概念實作,而物件的function是要算出該陣列中index範圍間的總合,基本上就是初始化時將值存入物件,最後在function去呼叫儲存在物件的陣列,用迴圈遍歷範圍值總合回傳就結束了。

程式碼解說:

首先先定義好要存在物件裡值的型別,接著當建構function被呼叫時將值帶入一個初始化的物件並回傳,最後在SumRange被呼叫時利用this來存取初始化帶入的陣列,並用迴圈遍歷範圍的index值做總合回傳

1
2
3
4
5
6
7
8
9
10
11
12
13
14
type NumArray struct {
Nums []int
}
func Constructor(nums []int) NumArray {
return NumArray{nums}
}
func (this *NumArray) SumRange(i int, j int) int {
var sum int
for i <= j {
sum += this.Nums[i]
i++
}
return sum
}

完整程式碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
type NumArray struct {
Nums []int
}
func Constructor(nums []int) NumArray {
return NumArray{nums}
}
func (this *NumArray) SumRange(i int, j int) int {
var sum int
for i <= j {
sum += this.Nums[i]
i++
}
return sum
}

總結:

物件概念的基本實作。

分享到