303. Range Sum Query - Immutable

problem

303. Range Sum Query - Immutable

solution

class NumArray {
public:
    NumArray(vector<int> nums) {
        accu.push_back(0);
        for (auto num:nums)
        {
            accu.push_back(accu.back()+num);
        }
    }
    
    int sumRange(int i, int j) {
        return accu[j+1] - accu[i];//err.
    }
private:
    vector<int> accu;
};

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(i,j);
 */

注意,累加和的下标,因为累加和的第一项是初始化值0.

 

参考

1. Leetcode_303_Range Sum Query - Immutable;

 

posted on 2019-02-22 09:39  鹅要长大  阅读(158)  评论(0编辑  收藏  举报

导航