1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| class NumArray {
private Node[] tree;
private int[] nums;
public NumArray(int[] nums) { this.nums = nums; this.tree = new Node[nums.length * 4]; buildTree(0, nums.length - 1, 1); }
public void update(int index, int val) { change(index, val, 1); }
public int sumRange(int left, int right) { return query(left, right, 1); }
public void buildTree(int left, int right, int p) { tree[p] = new Node(); tree[p].left = left; tree[p].right = right; if (left == right) { tree[p].sum = nums[left]; return; } int mid = (left + right) / 2; buildTree(left, mid, p * 2); buildTree(mid + 1, right, p * 2 + 1); tree[p].sum = tree[p * 2].sum + tree[p * 2 + 1].sum; }
public void change(int index, int val, int p) { if (tree[p].left == tree[p].right) { tree[p].sum = val; return; } int mid = (tree[p].left + tree[p].right) / 2; if (index <= mid) { change(index, val, p * 2); } else { change(index, val, p * 2 + 1); } tree[p].sum = tree[p * 2].sum + tree[p * 2 + 1].sum; }
public int query(int left, int right, int p) { if (tree[p].left >= left && tree[p].right <= right) { return tree[p].sum; } int mid = (tree[p].left + tree[p].right) / 2; int sum = 0; if (left <= mid) { sum += query(left, right, p * 2); } if (right > mid) { sum += query(left, right, p * 2 + 1); } return sum; }
class Node { public int left; public int right; public int sum;
public Node() {} } }
|