当前位置:网站首页>Leetcode-303: region and retrieval - array immutable
Leetcode-303: region and retrieval - array immutable
2022-07-07 10:27:00 【Chrysanthemum headed bat】
leetcode-303: Area and retrieval - The array is immutable
subject
Given an array of integers nums, Handle multiple queries of the following types :
- Calculation index left and right ( contain left and right) Between nums Elemental and , among left <= right
Realization NumArray class :
- NumArray(int[] nums) Using arrays nums Initialize object
- int sumRange(int i, int j) Returns an array of nums Middle index left and right Between elements The sum of the , contain left and right At two o 'clock ( That is to say nums[left] + nums[left + 1] + … + nums[right] )
Example 1:
Input :
["NumArray", "sumRange", "sumRange", "sumRange"]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
Output :
[null, 1, -1, -3]
explain :
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))
Problem solving
Method 1 : The prefix and
s[i]=nums[0]+nums[1]+....+nums[i-1];
If required nums[2]+nums[3]+nums[4] It only needs
seek s[4]-s[1] that will do .
So you can initialize , Just calculate each s[i] Value
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];
}
};
边栏推荐
- Multisim--软件相关使用技巧
- BigDecimal value comparison
- Study summary of postgraduate entrance examination in November
- 柏拉图和他的三个弟子的故事:如何寻找幸福?如何寻找理想伴侣?
- Prototype object in ES6
- table宽度比tbody宽度大4px
- @Transcation的配置,使用,原理注意事项:
- Methods of adding centerlines and centerlines in SolidWorks drawings
- [牛客网刷题 Day6] JZ27 二叉树的镜像
- [email protected] can help us get the log object quickly
猜你喜欢
随机推荐
The variables or functions declared in the header file cannot be recognized after importing other people's projects and adding the header file
Kotlin实现微信界面切换(Fragment练习)
Study summary of postgraduate entrance examination in November
原型与原型链
Trajectory planning for multi-robot systems: Methods and applications 综述阅读笔记
1324:【例6.6】整数区间
基于HPC场景的集群任务调度系统LSF/SGE/Slurm/PBS
P1031 [NOIP2002 提高组] 均分纸牌
Weekly recommended short videos: what are the functions of L2 that we often use in daily life?
基于gis三维可视化技术的智慧城市建设
嵌入式背景知识-芯片
5个chrome简单实用的日常开发功能详解,赶快解锁让你提升更多效率!
Yarn的基础介绍以及job的提交流程
SQLyog数据库怎么取消自动保存更改
The Hal library is configured with a general timer Tim to trigger ADC sampling, and then DMA is moved to the memory space.
Programming features of ISP, IAP, ICP, JTAG and SWD
Appx代码签名指南
How embedded engineers improve work efficiency
1323:【例6.5】活动选择
555电路详解






