LeetCode_前缀和_简单_303.区域和检索 - 数组不可变
2023-09-27 14:25:46 时间
1.题目
给定一个整数数组 nums,处理以下类型的多个查询:
计算索引 left 和 right (包含 left 和 right)之间的 nums 元素的和 ,其中 left <= right
实现 NumArray 类:
NumArray(int[] nums) 使用数组 nums 初始化对象
int sumRange(int i, int j) 返回数组 nums 中索引 left 和 right 之间的元素的总和 ,包含 left 和 right 两点(也就是 nums[left] + nums[left + 1] + … + nums[right] )
示例 1:
输入:
[“NumArray”, “sumRange”, “sumRange”, “sumRange”]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
输出:
[null, 1, -1, -3]
解释:
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))
提示:
0 <= nums.length <= 104
-105 <= nums[i] <= 105
0 <= i <= j < nums.length
最多调用 104 次 sumRange 方法
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/range-sum-query-immutable
2.思路
(1)前缀和
本题是一个典型的前缀和问题,主要思路是用一个新的数组 preSum 来记录 nums[0…i-1] 的累加和,那么如果想求数组 nums 索引区间 [left, right] 内的所有元素之和,可以直接通过一次减法运算 preSum[right+1] - preSum[left] 得到。
3.代码实现(Java)
//思路1————前缀和
class NumArray {
/*
前缀和数组preSum记录nums[0..i-1]的累加和
preSum[i]=nums[0]+...+nums[i-1]
*/
private int[] preSum;
public NumArray(int[] nums) {
//初始preSum[0] = 0
preSum = new int[nums.length + 1];
//计算数组nums的累加和
for (int i = 1; i < preSum.length; i++) {
preSum[i] = preSum[i - 1] + nums[i - 1];
}
}
//查询闭数组nums区间[left,right]的累加和
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);
*/
相关文章
- Leetcode: Unique Substrings in Wraparound String
- Leetcode: Contains Duplicate
- Leetcode: Plus One
- leetcode: Excel Sheet Column Number
- leetcode 214. 最短回文串 解题报告
- LeetCode高频题33. 搜索旋转排序数组
- LeetCode高频题4:求两个有序但不等长数组arr1,arr2,合成有序数组arr之后的上中位数是多少
- JS leetcode 合并两个有序数组 解题分析
- [LeetCode] Excel Sheet Column Title
- [LeetCode] Best Time to Buy and Sell Stock II
- [LeetCode]657. 机器人能否返回原点
- LeetCode 167. 两数之和 II - 输入有序数组
- 175、【动态规划】leetcode ——718. 最长重复子数组 (C++版本)
- 158、【动态规划】leetcode ——518. 零钱兑换 II:二维数组+一维滚动数组(C++版本)
- 【LeetCode】87. Scramble String
- [LeetCode] 1301. Number of Paths with Max Score 最大得分的路径数目
- [LeetCode] 909. Snakes and Ladders 蛇梯棋
- [LeetCode] 907. Sum of Subarray Minimums 子数组最小值之和
- [LeetCode] 718. Maximum Length of Repeated Subarray 最长的重复子数组
- [LeetCode] 457. Circular Array Loop 环形数组循环
- [LeetCode] 659. Split Array into Consecutive Subsequences 将数组分割成连续子序列
- [LeetCode] 554. Brick Wall 砖头墙壁
- [LeetCode] Triangle 三角形
- leetcode算法53.最大子数组和