6 lines concise and easy understand c++ solution


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

Log in to reply
 

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