Problem
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
ExampleGiven nums = [-2, 0, 3, -5, 2, -1]
Note</>复制代码
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
You may assume that the array does not change.
There are many calls to sumRange function.
只对nums进行修改,运用递归思想,非常好的解法。
Solution</>复制代码
public class NumArray {
int[] nums;
public NumArray(int[] nums) {
for(int i = 1; i < nums.length; i++)
nums[i] += nums[i - 1];
this.nums = nums;
}
public int sumRange(int i, int j) {
if(i == 0)
return nums[j];
return nums[j] - nums[i - 1];
}
}
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/64773.html
摘要:假设有一个整数数组,计算下标从到包含和的数字的和。求和的请求将会在同一个整数数组上多次请求。这一题思路很简单,因为。而利用动态规划则很容易知道。这里将原先的一维数组替换成二维数组。要求计算一个矩形内的所有元素的值。 Range Sum Query Immutable Given an integer array nums, find the sum of the elements be...
Problem Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). https://leetcode.com/static/i...s...
摘要:表现在二进制上的规律每次加上最末尾的求末尾的就拿这个数和它的补码于。还有要求不是,要转换一下,和之前那道的思路差不多。这里用一个的表示从到的和。 Range Sum Query - Immutable Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), i...
摘要:题目要求可以先参考数组不发生变动时的题目。最后的叶节点为当前数组的值,非叶结点则记录了子数组的范围以及该子数组中所有元素的和。它是一个非常轻量级的数据结构,而且几乎就是为这种题目量身打造。 题目要求 Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inc...
摘要:月下半旬攻略道题,目前已攻略题。目前简单难度攻略已经到题,所以后面会调整自己,在刷算法与数据结构的同时,攻略中等难度的题目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道题,目前已攻略 100 题。 一 目录 不折腾的前端,和咸鱼有什么区别...
阅读 3467·2023-04-26 00:57
阅读 692·2021-10-08 10:05
阅读 1439·2021-09-08 09:36
阅读 4295·2021-08-12 13:31
阅读 2655·2019-08-30 15:55
阅读 2295·2019-08-30 15:55
阅读 1106·2019-08-30 15:55
阅读 2765·2019-08-29 13:17
极致性价比!云服务器续费无忧!
Tesla A100/A800、Tesla V100S等多种GPU云主机特惠2折起,不限台数,续费同价。
NVIDIA RTX 40系,高性价比推理显卡,满足AI应用场景需要。
乌兰察布+上海青浦,满足东推西训AI场景需要