Share my Java solution


  • 0

    First get the accumulated sum[] and then for range [i, j], the sum is: sum[j] - sum[i-1], but be careful of the corner case when i equals to 0.

    public class NumArray {
      int[] sums;
      
      public NumArray(int[] nums) {
        sums = new int[nums.length];
        // accumulate the sum from nums[0] to nums[i]  
        for (int i = 0; i < nums.length; i++)
          sums[i] = nums[i] + ((i > 0) ? sums[i - 1] : 0);
      }
      
      public int sumRange(int i, int j) {
        return (i == 0) ? sums[j] : sums[j] - sums[i - 1];
      }
    }

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

    }

    Why my code is this and got an error, I think our solution is the same


  • 0

    Hi James, the input nums[] can be an empty array (one of the test cases is []), so when you try to access nums[0], you got runtime error :)


  • 0
    J

    thank you. I have revised my code


Log in to reply
 

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