LeetCode 307. Range Sum Query - Mutable
来源:互联网 发布:违规网络音乐名单李志 编辑:程序博客网 时间:2024/06/05 23:56
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:
Given nums = [1, 3, 5]sumRange(0, 2) -> 9update(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.
#include <vector>#include <iostream>using namespace std;// this is actually to use binary index tree.int getSum(vector<int>& BITree, int index) { int sum = 0; index = index + 1; while(index > 0) { sum += BITree[index]; index -= index & (-index); // update to its parent node in getSum view. } return sum;}void updateBITree(vector<int>& BITree, int index, int val) { index = index + 1; while(index < BITree.size()) { BITree[index] += val; index += index & (-index); // update to its parent node in update view }}vector<int> createBITree(vector<int>& nums) { int n = nums.size(); vector<int> BITree(n + 1, 0); for(int i = 0; i < n; ++i) { updateBITree(BITree, i, nums[i]); } return BITree;}int main(void) { vector<int> nums{1, 3, 5}; vector<int> BITree = createBITree(nums); updateBITree(BITree, 1, 2); cout << getSum(BITree, 2) << endl;}
Let's use an example to help explain how to organize a binary index tree.
Suppose we have a 10 size array [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Our target tree will be like this:
The picture above shows how is the binary index tree organized. There are several things to pay attentions to:
1: Update parent node is index += index & (-index)
2: GetSum parent node is index -= index &(-index)
3: BITree's first index is empty.
4: The parent index equals to change the child index's rightmost bit '1' into '0'.
0 0
- leetcode 307. Range Sum Query - Mutable
- LeetCode 307. Range Sum Query - Mutable
- Leetcode 307. Range Sum Query - Mutable (Python)
- LeetCode 307. Range Sum Query - Mutable
- [LeetCode]Range Sum Query - Mutable
- Range Sum Query - Mutable -leetcode
- leetcode Range Sum Query - Mutable
- Leetcode: Range Sum Query - Mutable
- Leetcode: Range Sum Query - Mutable
- leetcode, Range Sum Query - Mutable
- LeetCode Range Sum Query - Mutable
- leetcode - Range Sum Query - Mutable
- Range Sum Query - Mutable -- Leetcode
- leetcode Range Sum Query-Mutable
- 【Leetcode】Range Sum Query - Mutable
- 307. Range Sum Query - Mutable
- 307. Range Sum Query - Mutable
- 307. Range Sum Query - Mutable
- Android异步更新UI的四种方式
- iOS-程序的启动与运转-RunLoop个人小结
- 云计算+将成为一种新潮流 未来或将超越互联网+
- cocos2dx之c++11 bind
- Java中使用连接池技术链接数据库
- LeetCode 307. Range Sum Query - Mutable
- sendmessage死锁问题
- SharedPreferences篇
- BigInteger简析
- iOS定义UIColor RGB 的宏
- Thread 总结
- 随想(二)-- 基于负载均衡和本地锁的分布式锁
- apk签名
- 验证篇(5.2)-01. 域服务器认证 ❀ 飞塔 (Fortinet) 防火墙