303. Range Sum Query

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;

原文地址:https://www.cnblogs.com/happyamyhope/p/10416518.html