Just find my simple solution beats all, so put it here for your reference


  • -1
    B
    class NumArray {
        vector<int> incSum;
        vector<int> nums;
    public:
        NumArray(vector<int> &nums) {
            int s{};
            for(auto i: nums) {
                s += i;
                incSum.push_back(s);
                this->nums.push_back(i);
            }
        }
    
        int sumRange(int i, int j) {
            if (i == 0)
                return incSum[j];
            else
                return incSum[j] - incSum[i] + nums[i];
        }
    

    };


  • -1
    S

    I think the below is much simpler
    public class NumArray {
    int numbers[];
    public NumArray(int[] nums) {
    numbers=nums;
    }

    public int sumRange(int i, int j) {
        int sum=0;
    	for(int k=i;k<=j;k++){
    		sum=sum+numbers[k];
    	}
    	return sum; 
    }
    

    }


Log in to reply
 

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