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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| class NumArray { SegmentTree tree; public NumArray(int[] nums) { tree = new SegmentTree(nums); } public void update(int i, int val) { tree.update(i, val); } public int sumRange(int i, int j) { return tree.querySum(i, j); } static class SegmentTree{ Node root = null; SegmentTree(int[] array){ this.root = build(0, array.length-1, array); } Node build(int start, int end, int[] array){ if (start>end){ return null; } Node node = new Node(start, end); if (start==end){ node.sum = array[start]; return node; } int mid = start + (end-start)/2; node.left = build(start, mid, array); node.right = build(mid+1, end, array); node.sum = node.left.sum + node.right.sum; return node; } int querySum(int start, int end){ return querySum(root, start, end); } int querySum(Node root, int start, int end){ if (start>end){ return 0; } if (root.start==start && root.end==end){ return root.sum; } int mid = root.start + (root.end-root.start)/2; int leftsum = 0; int rightsum = 0; if (start<=mid){ leftsum = querySum(root.left, start, Math.min(mid, end)); } if (end>=mid+1){ rightsum = querySum(root.right, Math.max(mid+1, start), end); } return leftsum+rightsum; } void update(int index, int value){ update(root, index, value); } void update(Node root, int index, int value){ if (root.start==index && root.end==index){ root.sum = value; return; } int mid = root.start + (root.end-root.start)/2; if (index <= mid){ update(root.left, index, value); }else{ update(root.right, index, value); } root.sum = root.left.sum + root.right.sum; } } static class Node{ int start; int end; int sum; Node left; Node right; Node(int start, int end){ this.start = start; this.end = end; sum = 0; left = null; right = null; } } }
|