LeetCode——Range Sum Query - Immutable

Question

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

  • Note:
    You may assume that the array does not change.
    There are many calls to sumRange function.

Solution

简单的动态规划,依次累加,table[j] - table[i - 1]就表示两者之间的求和,注意i - 1可能越界。

Code

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

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(i,j);
 */
posted @ 2017-09-10 10:27  清水汪汪  阅读(121)  评论(0编辑  收藏  举报