leecode_307 Range Sum Query - Mutable
2016-06-14 04:23
435 查看
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
The update(i,
val) function modifies nums by
updating the element at index i to val.
Example:
Note:
The array is only modifiable by the update function.
You may assume the number of calls to update and sumRange function is distributed evenly.
给出一般的解法,update O(n), sumrange O(1);
树状数组的解法参考 http://blog.csdn.net/xyt8023y/article/details/49946789
The update(i,
val) function modifies nums by
updating the element at index i to val.
Example:
sumRange(0, 2) -> 9 update(1, 2) sumRange(0, 2) -> 8
Note:
The array is only modifiable by the update function.
You may assume the number of calls to update and sumRange function is distributed evenly.
给出一般的解法,update O(n), sumrange O(1);
class NumArray { public: vector<int> sum; vector<int> num_vec; NumArray(vector<int> &nums) { num_vec=nums; sum.push_back(0); for (int i=0;i<nums.size();i++) sum.push_back(sum[i]+nums[i]); } void update(int i, int val) { for (int j=i+1;j<sum.size();j++) sum[j]=sum[j]+val-num_vec[i]; num_vec[i]=val; } int sumRange(int i, int j) { return sum[j+1]-sum[i]; } }; // Your NumArray object will be instantiated and called as such: // NumArray numArray(nums); // numArray.sumRange(0, 1); // numArray.update(1, 10); // numArray.sumRange(1, 2);
树状数组的解法参考 http://blog.csdn.net/xyt8023y/article/details/49946789
相关文章推荐
- [LeetCode] Count Numbers with Unique Digits 计算各位不相同的数字个数
- Implement Queue using Stacks
- easyui的tab加载页面中的form重复提交
- IOS创建UI的方式
- CocoaPods问题: CocoaPods was not able to update the `master` repo.if it is a unexpected issue and
- [java线程]---BlockingQueue队列使用
- 揭密小米VR:VR界的MIUI什么样?
- iOS瀑布流简明教程之UICollectionView
- easyui 扩展loading
- easyui获取datagrid某一行记录
- UILabel,自定义cell的自适应高度
- Android学习-手把手教学实现仿微信发带图片朋友圈的UI设计
- HOTPOWER-中国十佳优秀UI设计团队,提供游戏UI顶级服务。
- iOS 中只 导两边圆角的UIButton
- Timer源码之TaskQueue
- Timer源码之TimerThread
- leetcode之Range Sum Query 2D - Immutable
- requireJS 简要介绍和完整例子
- OSG+Duilib显示osg
- OSG+Duilib显示osg