leetcode 303. Range Sum Query - Immutable

 关键在于,想出类似最大子数组和中的一种解法。

缓存每个数前的所有和,需要的时候,减一下即可。

class NumArray {
public:
    vector<int> sum;
    NumArray(vector<int> nums) {
        sum.push_back(0);
        for (int i = 0; i < nums.size(); i++)
            sum.push_back(sum[i] + nums[i]);
    }
    
    int sumRange(int i, int j) {
        return sum[j + 1] - sum[i];
    }
};

 

posted on 2018-02-08 14:42  willaty  阅读(82)  评论(0编辑  收藏  举报

导航