Accepted Java Range Sum Query Solution


  • 5
    V

    public class NumArray {

    int[] nums;
    int[] numSum;
    
    public NumArray(int[] nums) {
        this.nums = nums;
        numSum = new int[nums.length + 1];
        numSum[0] = 0;
        for(int i = 1; i < numSum.length; i++){
            numSum[i] = numSum[i - 1] + nums[i - 1];
        }
    }
    
    public int sumRange(int i, int j) {
        if(i < 0 || j >= nums.length){
            return 0;
        }
        
        return numSum[j + 1] - numSum[i];
    }
    

    }


Log in to reply
 

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