Easy Understanding Java Solution


  • 0

    Time Complexity for my solution is O(1) since every sum of the former elements has been calculated in the constructer, what you have to do in the sumRange method is only calculating once.

    Space Complexity is O(n) where n is the length of nums array.

    public class NumArray {
        
        private int[] sum;
    
        public NumArray(int[] nums) {
            sum = nums;
            //sum[i] = sum[0] + sum[1] + ... + sum[i]
            for(int i=1; i<nums.length; i++) {
                sum[i] += sum[i-1];
                System.out.println(sum[i]);
            }
        }
    
        public int sumRange(int i, int j) {
            if(i == 0) return sum[j];
            return sum[j]-sum[i-1];
        }
    }
    

Log in to reply
 

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