LeetCode-303. Range Sum Query
来源:互联网 发布:我国加工贸易知乎 编辑:程序博客网 时间:2024/06/06 03:07
问题:https://leetcode.com/problems/range-sum-query-immutable/?tab=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
给定一个整型数组nums,找出在索引i到j(i小于等于j)之间(包括i和j)的所有元素之和。
例如:给定nums = [-2,0,3,-5,2,-1]
sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3
批注:你可以假定这个数组不会改变。这里会有很多次对sumRange函数的调用。
分析:遍历 i 到 j ,累计得到和即可。但是,这样是TLE的。我们可以存储子序列和,每个下标处的值为[0,i]的所有元素和;那么[i,j]子序列和 =sum[j]−sum[i−1];
注意,i==0时,直接返回sum[j]即可。
C++代码:
class NumArray {public: NumArray(vector<int> nums) { if (nums.empty()) return ; else { sums.push_back(nums[0]); int len = nums.size(); for (int i = 1; i < len; ++i) { sums.push_back(sums[i - 1] + nums[i]); } } } int sumRange(int i, int j) { if (0 == i) return sums[j]; int len = sums.size(); if (i < 0 || i >= len || j < 0 || j >= len || i > j) { return 0; } return sums[j] - sums[i-1]; } private: //存储数列和 vector<int> sums;};/** * 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
- 项目上的红叉,或项目不能运行
- linux 权限说明
- JAVA学习日志:static关键字
- 如何用代码在Excel中实现单元格内换行
- Jquery的loading插件
- LeetCode-303. Range Sum Query
- 94. Binary Tree Inorder Traversal
- 仿饿了么加入购物车旋转控件
- Android Studio使用Ctrl+鼠标滚轮调整字体大小
- ecshop开发环境搭建
- MVC个人理解
- 获取系统日期
- [51NOD] 1004 n^n的末位数字 [数学]
- 简单理解时间复杂度怎么计算?