Java solution using sum array built in constructor.


  • 9
    C
    public class NumArray {
        int[] sum;
        public NumArray(int[] nums) {
            sum = new int[nums.length];
            if(nums.length>0)sum[0]=nums[0];
            for(int i=1; i<nums.length; i++){
                sum[i]=sum[i-1]+nums[i];
            }
        }
    
        public int sumRange(int i, int j) {
            if(i==0)return sum[j];
            return sum[j]-sum[i-1];
        }
    }

  • 0
    S

    Super cool solution!


  • 2
    X

    Or:

    public class NumArray {
        private final int[] sums;
    
        public NumArray(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(int i, int j) {
    	// return Arrays.stream(nums, i, j + 1).sum();            
    	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.