Given an integer array nums
, find the sum of the elements between indices i
and j
(i ≤ j)
, inclusive.
Implement the NumArray
class:
NumArray(int[] nums)
Initializes the object with the integer arraynums
.int sumRange(int i, int j)
Return the sum of the elements of thenums
array in the range[i, j]
inclusive (i.e.,sum(nums[i], nums[i + 1], ... , nums[j])
)
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 1 ((-2) + 0 + 3) numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1)) numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1))
Constraints:
0 <= nums.length <= 104
-105 <= nums[i] <= 105
0 <= i <= j < nums.length
- At most
104
calls will be made tosumRange
.
区域和检索 - 数组不可变。
给定一个整数数组 nums,求出数组从索引 i 到 j(i ≤ j)范围内元素的总和,包含 i、j 两点。
实现 NumArray 类:
NumArray(int[] nums) 使用数组 nums 初始化对象
int sumRange(int i, int j) 返回数组 nums 从索引 i 到 j(i ≤ j)范围内元素的总和,包含 i、j 两点(也就是 sum(nums[i], nums[i + 1], ... , nums[j]))来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/range-sum-query-immutable
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题求的是某一个范围内的数组元素的和,思路类似于前缀和。但是因为 int sumRange(int i, int j) 求的是闭区间 [i, j] 内所有元素的和所以我们创建一个 nums.length + 1 长度的数组记录前缀和。这样我们就能做到在求sumRange()这个函数的时候时间复杂度为O(1)了。
时间
prepare - O(n)
sumRange() - O(1)
空间O(n)
Java实现
1 class NumArray { 2 private int[] sum; 3 4 public NumArray(int[] nums) { 5 sum = new int[nums.length + 1]; 6 for (int i = 0; i < nums.length; i++) { 7 sum[i + 1] = sum[i] + nums[i]; 8 } 9 } 10 11 public int sumRange(int i, int j) { 12 return sum[j + 1] - sum[i]; 13 } 14 } 15 16 /** 17 * Your NumArray object will be instantiated and called as such: 18 * NumArray obj = new NumArray(nums); 19 * int param_1 = obj.sumRange(i,j); 20 */