LeetCode-Range Sum Query - Mutable
2016-03-28 11:01
483 查看
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.
Solution: it is an entry-level problem about Binary Indexed Tree.
Check BIT out: http://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/
The update(i, val) function modifies nums by updating the element at index i to val.
Example:
Given nums = [1, 3, 5] 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.
public class NumArray { private int[] tree; private int[] num; public NumArray(int[] nums) { tree = new int[nums.length]; num = new int[nums.length]; Arrays.fill(tree,0); Arrays.fill(num,0); for (int i=0;i<nums.length;i++){ update(i,nums[i]); } } void update(int i, int val) { int delta = val-num[i]; num[i] = val; int ind = i+1; while (ind<=tree.length){ tree[ind-1] += delta; ind += ind & (-ind); } } private int sum(int i){ int ind = i+1; int sum = 0; while (ind>0){ sum += tree[ind-1]; ind -= ind & (-ind); } return sum; } public int sumRange(int i, int j) { int a = sum(j); int b = sum(i-1); return a-b; } } // Your NumArray object will be instantiated and called as such: // NumArray numArray = new NumArray(nums); // numArray.sumRange(0, 1); // numArray.update(1, 10); // numArray.sumRange(1, 2);
Solution: it is an entry-level problem about Binary Indexed Tree.
Check BIT out: http://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/
相关文章推荐
- mysql-异常Incorrect string value: '\xF0\x9F...' for column 'XXX' at row 1
- [uivier removefromsuperview]之后别忘了设置为nil
- ui控件的属性一般都是weak,但是内部变量的属性都是强引用,一般我们都是创建一个内部变量,然后让控件引用属性指向内变量
- Gradle build.gradle to Maven pom.xml
- 对于要不断使用的uiview一般通过懒加载的形式,而不是创建一个销毁一个
- codeforces 652E . Pursuit For Artifacts 强连通分量
- hdu 5493 Queue 树状数组第K大或者二分
- 让UITableview里自定义分区头部随着滑动而滑动
- requireJs模块化实现返回顶部的功能
- BlockingQueue
- c# Dictionary的TryGetValue的用法
- iOS 动画讲解(一)之UIView动画
- OpenCV学习笔记---HighGUI的初步
- UML时序图画法简介-sequenceDiagram
- queue
- Xcode 插件因为UUID原因不能使用解决办法
- android 漂亮的开源ui框架
- 《iOS Human Interface Guidelines》——Progress View
- 背水一战 Windows 10 (5) - UI: 标题栏
- LeetCode Verify Preorder Sequence in Binary Search Tree