您的位置:首页 > 产品设计 > UI/UE

leetcode(303)Range Sum Query - Immutable js代码实现

2015-12-18 14:21 786 查看


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函数中写出需要的函数语句即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript prototype