---
# System prepended metadata

title: \#303 Range Sum Query - Immutable
tags: [leetcode, leetcode-easy]

---

# \#303 Range Sum Query - Immutable
## *建立一類別: 可傳入一數字陣列, 並有方法回傳該數字陣列的某連續範圍元素總和(sum=[left, right])*
## Log
 - build 20210614 by syhuang

## 較佳解
 - 在類別實體化的時候就先計算好各連續區間的元素和(因該方法只要求回傳連續區間範圍), 就可以在呼叫時直接用ary[right]-ary[left-1]取得left到right的總和, 降低了時間複雜度
```javascript=
var NumArray = function(nums) {
    let partNumSums = [];
    partNumSums[0] = nums[0];
    for(let i=1; i<nums.length; i++) partNumSums[i] = partNumSums[i-1] + nums[i];
    this.PART_NUM_SUMS = partNumSums;
};
NumArray.prototype.sumRange = function(left, right) {
    if(left==0) return this.PART_NUM_SUMS[right];
    return this.PART_NUM_SUMS[right] - this.PART_NUM_SUMS[left-1];
};
```
## 初見
 - 實作class, 在回傳範圍總和的時間複雜度為O(N)
```javascript=
var NumArray = function(nums) {
    this.NUMS = nums;
};
NumArray.prototype.sumRange = function(left, right) {
    let result = 0;
    for(let i=left; i<=right; i++) result+=this.NUMS[i]
    return result;
};
```
## 備註
## 參考
- [參考解](https://leetcode.com/problems/range-sum-query-immutable/discuss/75192/Java-simple-O(n)-init-and-O(1)-query-solution)
###### tags: `leetcode`, `leetcode-easy`