Simple and fast by pre-stored sum array


  • 0
    X
    private final int[] sums;
    
    public NumArray(final int[] nums) {
        this.sums = new int[nums.length + 1];
        for (int i = 0; i < nums.length; i++) {
            sums[i + 1] = nums[i] + sums[i];
        }
    }
    
    public int sumRange(final int i, final int j) {           
        return sums[j + 1] - sums[i];
    }
    

Log in to reply
 

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