LeetCode-Range Sum Query - Mutable

LiBlog發表於2016-03-28

Given an integer array nums, find the sum of the elements between indices i and j (ij), 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) -> 9
update(1, 2)
sumRange(0, 2) -> 8

Note:

    1. The array is only modifiable by the update function.
    2. You may assume the number of calls to update and sumRange function is distributed evenly.

 

 1 public class NumArray {
 2         private int[] tree;
 3         private int[] num;
 4 
 5         public NumArray(int[] nums) {
 6             tree = new int[nums.length];
 7             num = new int[nums.length];
 8             
 9             Arrays.fill(tree,0);
10             Arrays.fill(num,0);
11             for (int i=0;i<nums.length;i++){
12                 update(i,nums[i]);
13             }
14         }
15 
16         void update(int i, int val) {
17             int delta = val-num[i];
18             num[i] = val;
19             int ind = i+1;
20 
21             while (ind<=tree.length){
22                 tree[ind-1] += delta;
23                 ind += ind & (-ind);
24             }
25 
26         }
27 
28         private int sum(int i){
29             int ind = i+1;
30             int sum = 0;
31 
32             while (ind>0){
33                 sum += tree[ind-1];                
34                 ind -= ind & (-ind);
35             }
36             return sum;
37         }
38 
39         public int sumRange(int i, int j) {
40             int a = sum(j);
41             int b = sum(i-1);
42             return a-b;
43         }
44         
45         
46     }
47 
48 
49 // Your NumArray object will be instantiated and called as such:
50 // NumArray numArray = new NumArray(nums);
51 // numArray.sumRange(0, 1);
52 // numArray.update(1, 10);
53 // 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/

相關文章