C++ simple solution, O(n) to build, O(1) to query


  • 10
    F

    Use a vector to store the sum from 0 to i.

    class NumArray {
    public:
        vector<int> memo = {0};
        NumArray(vector<int> &nums) {
            int summ = 0;
            for (int n : nums) {
                summ += n;
                memo.push_back(summ);
            }
        }
    
        int sumRange(int i, int j) {
            return memo[j+1] - memo[i];
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.