Skip to main content

303 Range Sum Query - Immutable

Leetcode

Given an integer array nums, handle multiple queries of the following type:

Calculate the sum of the elements of nums between indices left and right inclusive where left <= right. Implement the NumArray class:

NumArray(int[] nums) Initializes the object with the integer array nums. int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).

Example 1:

Input ["NumArray", "sumRange", "sumRange", "sumRange"][[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
Output
[null, 1, -1, -3]

Explanation NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3

如果直接计算,时间复杂度 o(right-left) ,可以对数组进行预处理,实现 o(1)

class NumArray {
int[] total;

public NumArray(int[] nums) {
total=new int[nums.length+1];
for(int i=1;i<total.length;++i){
total[i]=total[i-1]+nums[i-1];
}
}

public int sumRange(int left, int right) {
return total[right+1]-total[left];
}
}