Range Sum Query

动态规划问题

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

NOTE:
1.
You may assume that the array does not change.
2.There are many calls to sumRange function.

个人总结:看到 Note2 应该想到这是一个动态规划问题,每次调用都去计算肯定会超时,因此应该提前把所有结果计算出来。
此外,一些特殊情况,比如nuns=[],i或者j可能越界,都得考虑到。
ac代码

public class NumArray{
    
     int[] array,sum;
   public NumArray(int[] nums) {
       if(nums.length==0||nums==null) return;
      array=nums;
      sum=nums;
      sum[0]=array[0];
      for(int i=1;i<array.length;i++){
         sum[i]=sum[i-1]+array[i];
       }
  }
  
  public int sumRange(int i,int j){
      if(sum==null||i>j||j>sum.length) return 0;
      
      else {
           if(i==0)  return sum[j];
           else
          return sum[j]-sum[i-1];     
          }
    }
  }


 
原文地址:https://www.cnblogs.com/summer323/p/5026307.html