LeetCode303-区域和检索 - 数组不可变-前缀和

原题链接
LeetCode303-区域和检索 - 数组不可变-前缀和_第1张图片

前缀和:
class NumArray {
public:
    vector<int> n;
    NumArray(vector<int>& nums) {
        n = vector<int>(nums.size() + 1, 0);
        for(int i = 1; i <= nums.size(); i ++)
            n[i] = nums[i - 1] + n[i - 1];
    }
    
    int sumRange(int left, int right) {
        return n[right + 1] - n[left];
    }
};

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray* obj = new NumArray(nums);
 * int param_1 = obj->sumRange(left,right);
 */

你可能感兴趣的:(leetcode,算法,数据结构,前缀和)