[LeetCode] 303. Range Sum Query - Immutable

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

Constraints:
1 <= nums.length <= 104
-105 <= nums[i] <= 105
0 <= left <= right < nums.length
At most 104 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]))

来源:力扣(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实现

class NumArray {
    int[] presum;

    public NumArray(int[] nums) {
        int n = nums.length;
        presum = new int[n + 1];
		// for循环按原数组的长度来,思考presum每个位置应该存什么,就不容易发生越界
		// 按如下这个规则写,前x项的前缀和是存在preSum[x + 1]位置上的
        for (int i = 0; i < n; i++) {
            presum[i + 1] = presum[i] + nums[i];
        }
    }
    
    public int sumRange(int left, int right) {
        return presum[right + 1] - presum[left];
    }
}

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(left,right);
 */

相关题目

303. Range Sum Query - Immutable
304. Range Sum Query 2D - Immutable
posted @ 2021-03-01 13:39  CNoodle  阅读(140)  评论(0编辑  收藏  举报