【LeetCode】303. Range Sum Query - Immutable 区域和检索 - 数组不可变(Easy)(JAVA)
题目地址: https://leetcode.com/problems/range-sum-query-immutable/
题目描述:
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 array nums.
- int sumRange(int i, int j) Return the sum of the elements of the nums 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 <= 10^4
- -10^5 <= nums[i] <= 10^5
- 0 <= i <= j < nums.length
- At most 10^4 calls will be made to sumRange.
题目大意
给定一个整数数组 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]))
解题方法
- 要计算 nums[i] + … + nums[j], 可以用前缀和的方式: sum[j] - sum[i - 1]
- 空间复杂度: O(n), 时间复杂度: O(1)
class NumArray {
private int[] sum;
public NumArray(int[] nums) {
sum = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
if (i == 0) {
sum[i] = nums[i];
} else {
sum[i] = sum[i - 1] + nums[i];
}
}
}
public int sumRange(int i, int j) {
if (i == 0) return sum[j];
return sum[j] - sum[i - 1];
}
}
执行耗时:10 ms,击败了77.14% 的Java用户
内存消耗:41.4 MB,击败了46.31% 的Java用户