Simple c++ solution O(1) time O(n) space


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

  • 7
    S
    class NumArray {
        vector<int> ret = {0};
    public:
        NumArray(vector<int> &nums) {
            for(auto n:nums) 
                ret.push_back(ret.back() + n);
        }
    
        int sumRange(int i, int j) {
            return ret[j+1] - ret[i];
        }
    };

Log in to reply
 

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