[LeetCode] Range Sum Query - Immutable

简介: Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.Example: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRang

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

解题思路

考虑到要多次调用sumRange()函数,因此需要把结果先存起来,调用时就可以直接返回了。最开始考虑的是用dp[i][j]来直接存储ij之间元素的和,但是内存超出限制。于是考虑用dp[i]来存储0i之间元素的和,0j的和减去0i-1的和即为所求。

实现代码

// Runtime: 3 ms
public class NumArray {
    private int[] dp;
    public NumArray(int[] nums) {
        dp = new int[nums.length];
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            dp[i] = sum;
        }
    }

    public int sumRange(int i, int j) {
        return i == 0 ? dp[j] : dp[j] - dp[i - 1];
    }
}

// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
目录
相关文章
LeetCode 307. Range Sum Query - Mutable
update(i, val) 函数可以通过将下标为 i 的数值更新为 val,从而对数列进行修改。
98 0
LeetCode 307. Range Sum Query - Mutable
LeetCode 304. Range Sum Query 2D - Immutable
给定一个二维矩阵,计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2)。
96 0
LeetCode 304. Range Sum Query 2D - Immutable
|
索引
LeetCode 303. Range Sum Query - Immutable
给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。
87 0
LeetCode 303. Range Sum Query - Immutable
LeetCode 201. Bitwise AND of Numbers Range
给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。
65 0
LeetCode 201. Bitwise AND of Numbers Range
|
索引 Python
LeetCode 307 Range Sum Query - Mutable(范围和查询-可变)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/51782135 翻译 给定一个整型数组nums,找出在索引i到j之间的元素的和(i 9 update(1, 2) sumRange(0, 2) -> 8 备注: 该数组只能被update函数修改。
924 0
|
算法
LeetCode 304 Range Sum Query 2D - Immutable(范围求和2D - 不可变)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/51783388 翻译 给定一个2D矩阵matrix,找出其中以左上角(row1,col1)和右下角(row2,col2)定义的矩形边界的元素的和。
914 0
|
测试技术 索引 Python
LeetCode 303 Range Sum Query - Immutable(范围总和查询-永久不变)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50611359 翻译 给定一个整型数组nums,找出在索引i到j(i小于等于j)之间(包括i和j)的所有元素之和。
796 0
|
11天前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
2月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
46 6