当前位置:网站首页>leetcode-303:区域和检索 - 数组不可变
leetcode-303:区域和检索 - 数组不可变
2022-07-07 08:18:00 【菊头蝙蝠】
题目
给定一个整数数组 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))
解题
方法一:前缀和
s[i]=nums[0]+nums[1]+....+nums[i-1];
如果要求 nums[2]+nums[3]+nums[4] 只需要
求s[4]-s[1]即可。
因此可以在初始化的时候,就去计算出每个s[i]的值
class NumArray {
public:
vector<int> sums;
NumArray(vector<int>& nums) {
int n=nums.size();
sums.resize(n+1);
for(int i=1;i<=nums.size();i++){
sums[i]=sums[i-1]+nums[i-1];
}
}
int sumRange(int left, int right) {
return sums[right+1]-sums[left];
}
};
边栏推荐
- Slurm资源管理与作业调度系统安装配置
- Socket通信原理和实践
- Study summary of postgraduate entrance examination in July
- C logging method
- High number_ Chapter 1 space analytic geometry and vector algebra_ Quantity product of vectors
- Multisim--软件相关使用技巧
- 单片机(MCU)最强科普(万字总结,值得收藏)
- Use of JSON extractor originals in JMeter
- Study summary of postgraduate entrance examination in November
- This article explains the complex relationship between MCU, arm, muc, DSP, FPGA and embedded system
猜你喜欢
随机推荐
Chris LATTNER, the father of llvm: why should we rebuild AI infrastructure software
Study summary of postgraduate entrance examination in November
Use of JSON extractor originals in JMeter
Experience sharing of software designers preparing for exams
Hdu-2196 tree DP learning notes
Study summary of postgraduate entrance examination in September
IPv4套接字地址结构
Advanced function learning in ES6
mysql插入数据创建触发器填充uuid字段值
成为优秀的TS体操高手 之 TS 类型体操前置知识储备
JMeter loop controller and CSV data file settings are used together
【华为机试真题详解】高矮个子排队
ORM -- grouping query, aggregation query, query set queryset object properties
ORM -- query type, association query
The variables or functions declared in the header file cannot be recognized after importing other people's projects and adding the header file
table宽度比tbody宽度大4px
[sword finger offer] 42 Stack push in and pop-up sequence
【HigherHRNet】 HigherHRNet 详解之 HigherHRNet的热图回归代码
STM32中AHB总线_APB2总线_APB1总线这些是什么
A small problem of bit field and symbol expansion









