|
| 1 | +// Source : https://leetcode.com/problems/range-sum-query-mutable/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2015-11-24 |
| 4 | + |
| 5 | +/*************************************************************************************** |
| 6 | + * |
| 7 | + * Given an integer array nums, find the sum of the elements between indices i and j (i |
| 8 | + * ≤ j), inclusive. |
| 9 | + * |
| 10 | + * The update(i, val) function modifies nums by updating the element at index i to val. |
| 11 | + * |
| 12 | + * Example: |
| 13 | + * |
| 14 | + * Given nums = [1, 3, 5] |
| 15 | + * |
| 16 | + * sumRange(0, 2) -> 9 |
| 17 | + * update(1, 2) |
| 18 | + * sumRange(0, 2) -> 8 |
| 19 | + * |
| 20 | + * Note: |
| 21 | + * |
| 22 | + * The array is only modifiable by the update function. |
| 23 | + * You may assume the number of calls to update and sumRange function is distributed |
| 24 | + * evenly. |
| 25 | + * |
| 26 | + ***************************************************************************************/ |
| 27 | + |
| 28 | + |
| 29 | +// The following idea is using `Binary Index Tree` |
| 30 | +// There are two articles explaine this technique quite well: |
| 31 | +// 1) http://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/ |
| 32 | +// 2) http://cs.stackexchange.com/questions/10538/bit-what-is-the-intuition-behind-a-binary-indexed-tree-and-how-was-it-thought-a |
| 33 | + |
| 34 | +class NumArray { |
| 35 | +private: |
| 36 | + int _sz; |
| 37 | + vector<int> _nums; |
| 38 | + vector<int> _sums; |
| 39 | +public: |
| 40 | + NumArray(vector<int> &nums) { |
| 41 | + _sz = nums.size(); |
| 42 | + _nums.resize(_sz+1, 0); |
| 43 | + _sums.resize(_sz+1, 0); |
| 44 | + for(int i=0; i< _sz; i++) { |
| 45 | + update(i, nums[i]); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + void update(int i, int val) { |
| 50 | + int oldv = _nums[i+1]; |
| 51 | + for(int idx = i+1; idx <= _sz; idx += (idx & (-idx)) ) { |
| 52 | + _sums[idx] = _sums[idx] - oldv + val; |
| 53 | + } |
| 54 | + _nums[i+1] = val; |
| 55 | + } |
| 56 | + |
| 57 | + int sumRange(int i, int j) { |
| 58 | + return sumRange(j+1) - sumRange(i); |
| 59 | + } |
| 60 | + |
| 61 | + int sumRange(int i) { |
| 62 | + int ret = 0; |
| 63 | + for(int idx=i; idx>0; idx -= (idx & (-idx)) ) { |
| 64 | + ret += _sums[idx]; |
| 65 | + } |
| 66 | + return ret; |
| 67 | + } |
| 68 | +}; |
| 69 | + |
| 70 | + |
| 71 | +// Your NumArray object will be instantiated and called as such: |
| 72 | +// NumArray numArray(nums); |
| 73 | +// numArray.sumRange(0, 1); |
| 74 | +// numArray.update(1, 10); |
| 75 | +// numArray.sumRange(1, 2); |
0 commit comments