Why my code has run time error in java(last executed input:[])?


  • 0
    S
    public class NumArray {
        private int[] nums;
        private int[] sums;
    public NumArray(int[] nums) {
        this.nums = nums;
        if(nums==null) {
            return;
        } 
        int len = nums.length;
        sums = new int[len];
        sums[0] = nums[0];
        for(int i=1;i<len;i++) {
            sums[i] = nums[i]+sums[i-1];
        }
    }
    
    public int sumRange(int i, int j) {
        if(i==0) {
            return sums[j];
        } else {
            return sums[j]-sums[i-1];
        }  
    }
    

    }


  • 0
    Y
    public class NumArray {
        private int[] nums;
        private int[] sums;
    public NumArray(int[] nums) {
        this.nums = nums;
        if(nums==null) {
            return;
        } 
        int len = nums.length;
        sums = new int[len];
        if(nums.length==0) sums=null;  //add it
        else {
            sums[0] = nums[0];
        for(int i=1;i<len;i++) {
            sums[i] = nums[i]+sums[i-1];
         }
        }
    }
    
    public int sumRange(int i, int j) {
        if(i==0) {
            return sums[j];
        } else {
            return sums[j]-sums[i-1];
        }  
    }
    }
    
    // Your NumArray object will be instantiated and called as such:
    // NumArray numArray = new NumArray(nums);
    // numArray.sumRange(0, 1);
    // numArray.sumRange(1, 2);

Log in to reply
 

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