Given an integer array nums
, handle multiple queries of the following type:
- Calculate the sum of the elements of
nums
between indicesleft
andright
inclusive whereleft <= right
.
Implement the NumArray
class:
NumArray(int[] nums)
Initializes the object with the integer arraynums
.int sumRange(int left, int right)
Returns the sum of the elements ofnums
between indicesleft
andright
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
Constraints:
1 <= nums.length <= 104
-105 <= nums[i] <= 105
0 <= left <= right < nums.length
- At most
104
calls will be made tosumRange
.
Accepted
397,212
Submissions
如果按照正常的想法很简单,就是在query的时候每次加一遍。但是因为构造的次数少,query的次数多,所以需要optimize query的时间复杂度,达到O(n)构造,O(1) query。那么构造的时候就可以存放当前index之前的数字和,query的时候只需要二者相减就行。但是需要注意的是,query时两个相减,如果left是0的话,应该直接返回right的值。
Runtime: 21 ms, faster than 49.58% of Java online submissions for Range Sum Query - Immutable.
Memory Usage: 48.8 MB, less than 65.91% of Java online submissions for Range Sum Query - Immutable.
class NumArray {
int[] sums;
public NumArray(int[] nums) {
sums = new int[nums.length];
sums[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
sums[i] = sums[i - 1] + nums[i];
}
}
public int sumRange(int left, int right) {
if (left == 0) {
return sums[right];
}
return sums[right] - sums[left - 1];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(left,right);
*/