classNumArray{privateint dp[]=null;//dp数组,一维表示,保存从0开始的区间(0,0),(0,1),(0,2)...(0,n)publicNumArray(int[] nums){this.dp =newint[nums.length];//让dp数组与nums数组长度保持一致this.dp[0]= nums[0];//(0,0)区间只有一个元素值nums[0]//保存其余从0开始的区间, 例如(0,1)区间 = (0,0)区间+nums[1]本身for(int i =1;i<nums.length;i++){
dp[i]= dp[i-1]+nums[i];}}publicintsumRange(int left,int right){if(left ==0)return dp[right];//如果是从0开始的区间,直接返回dp中的值即可elsereturn dp[right]-dp[left-1];//不是从0开始,需要特殊处理,(2,5) = (0,5) - (0,1)}}/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(left,right);
*/