Sharing my 585ms C++ solution


  • 2
    T
    class NumArray {
    private:
        vector<int> sums;
    public:
        NumArray(vector<int> &nums) {
            int n = nums.size();
            sums.resize(n, 0);
            int sum = 0;
            for(int i=0; i<n; i++)
            {
                sums[i] = sum + nums[i];
                sum = sums[i];
            }
        }
    
        int sumRange(int i, int j) {
            if(i==0)
                return sums[j];
            else
                return (sums[j] - sums[i-1]);
        }
    };
    
    
    // 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.