C++ solution with accumulated sum array


  • 4
    D
    class NumArray {
    public:
        NumArray(vector<int> &nums) {
        int accum=0;
        for(int i=0;i<nums.size();i++)
            {
            accum+=nums[i];
            _acarray.push_back(accum);
            }
        }
    
        int sumRange(int i, int j) {
            if(i==0)
                return (_acarray[j]);
            else 
                return (_acarray[j]-_acarray[i-1]);
        }
        
    private:
        vector<int> _acarray;
    };
    
    
    // Your NumArray object will be instantiated and called as such:
    // NumArray numArray(nums);
    // numArray.sumRange(0, 1);
    // numArray.sumRange(1, 2);

Log in to reply
 

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