Sum Query - Immutable
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.
JavaScript代碼實現
/**
* @constructor
* @param {number[]} nums
*/
var NumArray = function(nums) {
this.nums = nums;
for(i = 1; i < nums.length; i++){
this.nums[i] += this.nums[i - 1];
}
};
/**
* @param {number} i
* @param {number} j
* @return {number}
*/
NumArray.prototype.sumRange = function(i, j) {
if(i == 0){
return this.nums[j];
}
return this.nums[j] - this.nums[i - 1];
};
剛剛看到這個問題的時候可能會想到用循環來查找每次所需要的區間進行相加,但是這種方法提交上去不會accept,因爲這並不是最佳的方法,注意題目中所說的,You may assume that the array does not change.我們可以假設數組是不變的,那麼我們可以在NumArray 類中一次求出所有從第一個數到第n個數的和,根據提示,在sumRange函數中寫出需要的函數語句即可。