Leetcode:303. Range Sum Query
来源:互联网 发布:杭州明霖 知乎 编辑:程序博客网 时间:2024/06/06 14:02
Description:
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
解题思路
本题就是求区间内的所有数字之和,数组的数字及其下标不会改变。一开始会习惯性的采用传统的遍历相加求解,但该算法无法通过Leetcode;因此此时就要考虑重新设一个数组sum用于累积数字之和,其中sum[i+1]表示【0,i】区间的数字之和,那么【i,j】就可表示为sum[j+1]-sum[i],应注意的是i =0 时sum【i】= 0
代码
class NumArray {public: NumArray(vector<int> nums) { sum.push_back(0); for (int i = 0; i < nums.size();i++) { sum.push_back(sum.back()+nums[i]); } } int sumRange(int i, int j) { return sum[j+1]-sum[i]; } vector<int> sum;};/** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(i,j);
阅读全文
0 0
- 303.[LeetCode]Range Sum Query
- LeetCode-303. Range Sum Query
- [LeetCode]303. Range Sum Query
- LeetCode#303. Range Sum Query
- leetcode 303. Range Sum Query
- [LeetCode]303. Range Sum Query
- LeetCode 303. Range Sum Query
- LeetCode 303. Range Sum Query
- LeetCode 303. Range Sum Query
- leetcode-303. Range Sum Query
- LeetCode 303. Range Sum Query
- leetcode.303.Range Sum Query
- leetcode 303. Range Sum Query
- leetcode 303. Range Sum Query
- [leetcode]: 303. Range Sum Query
- [Leetcode] 303. Range Sum Query
- [LeetCode]303. Range Sum Query
- leetcode 303. Range Sum Query
- opencv3.3.0+python3.6.3学习笔记十一--百度大脑人脸识别匹配
- Java高级篇-2-装箱和拆箱的基本概念
- 项目总结:石头剪刀布小游戏
- ACM所有算法
- 分组背包
- Leetcode:303. Range Sum Query
- UE4-C++核心编程之接口---C++中的接口
- 重磅:传ARM生态系统负责人Leon离职创业,疑投身VR
- 流畅度秒杀苹果:vivo Xplay5视频曝光“黑科技”智慧引擎
- 上下曲面!vivo Xplay5正面曝光 全球首款6GB运存跑分超16万
- QQ浏览器带来的竞争启示:如何让用户在入口被“黏住”
- 工信部和国家空管法领导考察FLYPRO飞豹无人机,监管法案或将出台
- 虚拟机非正常关闭的解决方案
- GCC源码