首页 > 其他 > 详细

Range Sum Query - Immutable

时间:2017-01-01 18:57:27      阅读:201      评论:0      收藏:0      [点我收藏+]

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);
 */

 

Range Sum Query - Immutable

原文:http://www.cnblogs.com/agentgamer/p/6241293.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!