[LeetCode]--303. 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) -> 1sumRange(2, 5) -&

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:
You may assume that the array does not change.
There are many calls to sumRange function.

我最开始用的就是把数组的元素相加,因为知道i,j嘛,可以依次相加,但是这样就会超时。

如果最开始在构造函数里面构造数组的时候就把和都存进去,这样既可。

public class NumArray {

    public int[] nums;

    public NumArray(int[] nums) {
        if (nums.length == 0)
            return;
        this.nums = new int[nums.length];
        Arrays.fill(this.nums, 0);
        this.nums[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            this.nums[i] = this.nums[i - 1] + nums[i];
        }
    }

    public int sumRange(int i, int j) {
        if (this.nums.length == 0)
            return 0;
        if (j > this.nums.length - 1)
            j = this.nums.length - 1;
        if (i == 0)
            return this.nums[j];
        return this.nums[j] - this.nums[i - 1];
    }
}
目录
相关文章
LeetCode 307. Range Sum Query - Mutable
update(i, val) 函数可以通过将下标为 i 的数值更新为 val,从而对数列进行修改。
76 0
LeetCode 307. Range Sum Query - Mutable
LeetCode 304. Range Sum Query 2D - Immutable
给定一个二维矩阵,计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2)。
78 0
LeetCode 304. Range Sum Query 2D - Immutable
|
索引
LeetCode 303. Range Sum Query - Immutable
给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。
67 0
LeetCode 303. Range Sum Query - Immutable
LeetCode 201. Bitwise AND of Numbers Range
给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。
51 0
LeetCode 201. Bitwise AND of Numbers Range
|
测试技术 索引 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)的所有元素之和。
779 0
|
1天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
6 0
|
1天前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
7 0
|
2天前
|
算法
【刷题】 leetcode 面试题 08.05.递归乘法
递归算法是一种在计算机科学和数学中广泛应用的解决问题的方法,其基本思想是利用问题的自我相似性,即将一个大问题分解为一个或多个相同或相似的小问题来解决。递归算法的核心在于函数(或过程)能够直接或间接地调用自身来求解问题的不同部分,直到达到基本情况(也称为基础案例或终止条件),这时可以直接得出答案而不必再进行递归调用。 ———————————————— 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 原文链接:https://blog
15 4
【刷题】 leetcode 面试题 08.05.递归乘法
|
2天前
|
存储 算法 安全
【刷题】 leetcode 面试题 01.06 字符串压缩
来看效果: 非常好!!!过啦!!!
22 5

热门文章

最新文章