|
| 1 | +/******************************************* |
| 2 | +Author : LHearen |
| 3 | + |
| 4 | +Time : 2016-03-09 16:38 |
| 5 | +Description : Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. |
| 6 | +
|
| 7 | +The update(i, val) function modifies nums by updating the element at index i to val. |
| 8 | +Example: |
| 9 | +Given nums = [1, 3, 5] |
| 10 | +
|
| 11 | +sumRange(0, 2) -> 9 |
| 12 | +update(1, 2) |
| 13 | +sumRange(0, 2) -> 8 |
| 14 | +Note: |
| 15 | +The array is only modifiable by the update function. |
| 16 | +You may assume the number of calls to update and sumRange function is distributed evenly. |
| 17 | +Source : https://leetcode.com/problems/range-sum-query-mutable/ |
| 18 | +Reference : http://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/ |
| 19 | +*******************************************/ |
| 20 | +#include <stdlib.h> |
| 21 | +struct NumArray |
| 22 | +{ |
| 23 | + int *nums, *sums; |
| 24 | + int size; |
| 25 | +}; |
| 26 | + |
| 27 | +//partial sums are stored in numArray->sums; |
| 28 | +//index of sums are 1 more than that in nums; |
| 29 | +void updateElement(struct NumArray* numArray, int i, int val) |
| 30 | +{ |
| 31 | + i++; |
| 32 | + while(i <= numArray->size) |
| 33 | + { |
| 34 | + numArray->sums[i] += val; |
| 35 | + i += (i & -i); //move to its parent i UpdateView; |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +struct NumArray* NumArrayCreate(int *nums, int size) |
| 40 | +{ |
| 41 | + struct NumArray *t = (struct NumArray*)malloc(sizeof(struct NumArray)); |
| 42 | + t->nums = (int*)malloc(sizeof(int)*size); |
| 43 | + memcpy(t->nums, nums, sizeof(int)*size); |
| 44 | + t->size = size; |
| 45 | + t->sums = (int*)malloc(sizeof(int)*(size+1)); |
| 46 | + memset(t->sums, 0, sizeof(int)*(size+1)); |
| 47 | + for(int i = 0; i <= size; i++) |
| 48 | + updateElement(t, i, nums[i]); |
| 49 | + return t; |
| 50 | +} |
| 51 | + |
| 52 | +void update(struct NumArray* numArray, int i, int val) |
| 53 | +{ |
| 54 | + int d = val-numArray->nums[i]; |
| 55 | + numArray->nums[i] = val; |
| 56 | + updateElement(numArray, i, d); |
| 57 | +} |
| 58 | + |
| 59 | +//partial sums are stored in numArray->sums; |
| 60 | +//index of sums are 1 more than that in nums; |
| 61 | +int getSum(struct NumArray* numArray, int i) |
| 62 | +{ |
| 63 | + int sum = 0; |
| 64 | + i++; |
| 65 | + while(i > 0) |
| 66 | + { |
| 67 | + sum += numArray->sums[i]; |
| 68 | + i -= (i & -i); //move to its parent in getSumView; |
| 69 | + } |
| 70 | + return sum; |
| 71 | +} |
| 72 | +int sumRange(struct NumArray* numArray, int i, int j) |
| 73 | +{ |
| 74 | + return getSum(numArray, j)-getSum(numArray, i-1); |
| 75 | +} |
| 76 | + |
| 77 | +void NumArrayFree(struct NumArray* numArray) |
| 78 | +{ |
| 79 | + free(numArray->nums); |
| 80 | + free(numArray->sums); |
| 81 | + free(numArray); |
| 82 | +} |
0 commit comments