Range Sum Query

https://leetcode.com/problems/range-sum-query-immutable/

用缓存撒

/**
 * @constructor
 * @param {number[]} nums
 */
var NumArray = function(nums) {
    this.nums = nums;
    this.cache = [];
    var acc = 0;
    for (var i = 0; i < nums.length; i++) {
        acc += nums[i];
        this.cache.push(acc);
    }
};

/**
 * @param {number} i
 * @param {number} j
 * @return {number}
 */
NumArray.prototype.sumRange = function(i, j) {
    if (this.cache.length === 0) return 0;
    return this.cache[j] - this.cache[i] + this.nums[i];
};


/**
 * Your NumArray object will be instantiated and called as such:
 * var numArray = new NumArray(nums);
 * numArray.sumRange(0, 1);
 * numArray.sumRange(0, 2);
 */
原文地址:https://www.cnblogs.com/agentgamer/p/6241293.html