image.png

思路

计算前缀和
image.png

  1. class NumArray {
  2. private int[] sum;
  3. public NumArray(int[] nums) {
  4. sum = new int[nums.length+1];
  5. //计算前缀和
  6. for(int i=0;i<nums.length;i++)
  7. sum[i+1] = sum[i]+nums[i];
  8. }
  9. public int sumRange(int i, int j) {
  10. //用前缀和进行求区间和
  11. return sum[j+1]-sum[i];
  12. }
  13. }