当前位置:网站首页>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];
}
};
边栏推荐
- Postman interface test VI
- leetcode-560:和为 K 的子数组
- [牛客网刷题 Day5] JZ77 按之字形顺序打印二叉树
- [detailed explanation of Huawei machine test] tall and short people queue up
- Adb 实用命令(网络包、日志、调优相关)
- Socket通信原理和实践
- Why is the reflection efficiency low?
- The mobile terminal automatically adjusts the page content and font size by setting rem
- Review of the losers in the postgraduate entrance examination
- 555电路详解
猜你喜欢
随机推荐
Postman interface test VI
浅谈日志中的返回格式封装格式处理,异常处理
Postman interface test IV
[email protected] can help us get the log object quickly
【acwing】786. Number k
Methods of adding centerlines and centerlines in SolidWorks drawings
[second on] [jeecgboot] modify paging parameters
IPv4 socket address structure
【HigherHRNet】 HigherHRNet 详解之 HigherHRNet的热图回归代码
ORM -- grouping query, aggregation query, query set queryset object properties
STM32 Basics - memory mapping
5个chrome简单实用的日常开发功能详解,赶快解锁让你提升更多效率!
PDF文档签名指南
大整数类实现阶乘
Weekly recommended short videos: what are the functions of L2 that we often use in daily life?
Fiddler simulates the interface test
The width of table is 4PX larger than that of tbody
P1031 [NOIP2002 提高组] 均分纸牌
[email protected]能帮助我们快速拿到日志对象
Adb 实用命令(网络包、日志、调优相关)








