Range Sum Query
来源:互联网 发布:约瑟夫环java 编辑:程序博客网 时间:2024/05/16 11:11
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
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
自己首先写了一个方法:
class NumArray {public: NumArray(vector<int> nums) { int res = 0; for(int i = 0 ; i < nums.size(); ++i){ p_num.push_back(nums[i]); res+=nums[i]; s_num.push_back(res); } } int sumRange(int i, int j) { return s_num[j] - s_num[i] + p_num[i]; }private: vector<int> p_num; vector<int> s_num;};
然而这种方法效率低,开辟了多个空间,又要对其赋值。 较好的方法如下:
class NumArray {public: NumArray(vector<int> &nums) : psum(nums.size()+1, 0) { partial_sum( nums.begin(), nums.end(), psum.begin()+1); } int sumRange(int i, int j) { return psum[j+1] - psum[i]; }private: vector<int> psum; };
0 0
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- [Leetcode]Range Sum Query
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- 303,Range Sum Query
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Mutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Javacript
- Range Sum Query - Immutable
- Range Sum Query - Mutable
- Range Sum Query - Immutable
- android中,给dialog添加动画
- ssh免密码登陆设置时Authentication refused: bad ownership or modes错误解决方法
- Django学习2-使用模板
- PAT乙级1062
- 数据结构之栈和队列
- Range Sum Query
- [python爬虫] 招聘信息定时系统 (一).BeautifulSoup爬取信息并存储MySQL
- MySQL Group Replication 节点状态详解
- Shell——输入/输出重定向
- Android解压/重新打包system.img
- Linux内核学习总结
- AngularJS的方法
- 百练_2765八进制小数
- java基础总结16-面向对象12(接口)