303. Range Sum Query - Immutable

2018/04/27 leetcode 共 543 字,约 2 分钟

Title

the problem link

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example:
Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

Solution

DP解决,用数组保存以前的和

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

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

Search

    Table of Contents