LeetCode Range Sum Query - Mutable

来源:互联网 发布:html怎么外链js 编辑:程序博客网 时间:2024/04/27 16:37

Description:

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

Solution:

线段树模板


<span style="font-size:18px;">public class NumArray {SegmentTree st;int[] nums;public NumArray(int[] nums) {if (nums.length == 0)return;this.nums = nums;st = new SegmentTree(nums);}void update(int i, int val) {int change = val - nums[i];nums[i] = val;i++;st.update(i, change, 1);}public int sumRange(int i, int j) {i++;j++;return st.query(i, j, 1);}class SegmentTree {int[] lazy;int n;node[] nodes;SegmentTree(int[] arr) {this.n = arr.length;lazy = new int[n + 1];for (int i = 1; i <= n; i++)lazy[i] = arr[i - 1];nodes = new node[n * 3 + 1];build(1, n, 1);}public int build(int left, int right, int idx) {nodes[idx] = new node();nodes[idx].left = left;nodes[idx].right = right;if (left == right)return nodes[idx].lazy = lazy[left];int mid = (left + right) >> 1;return nodes[idx].lazy = build(left, mid, idx << 1)+ build(mid + 1, right, idx << 1 | 1);}public void update(int key, int x, int idx) {nodes[idx].lazy += x;if (nodes[idx].left == nodes[idx].right)return;int mid = nodes[idx].calmid();if (key <= mid)update(key, x, idx << 1);elseupdate(key, x, idx << 1 | 1);}public int query(int left, int right, int idx) {if (left == nodes[idx].left && right == nodes[idx].right)return nodes[idx].lazy;int mid = nodes[idx].calmid();if (mid >= right)return query(left, right, idx << 1);if (mid < left)return query(left, right, idx << 1 | 1);return query(left, mid, idx << 1)+ query(mid + 1, right, idx << 1 | 1);}}class node {int left, right, lazy;int calmid() {return (left + right) >> 1;}}public static void main(String[] args) {int nums[] = { 9, -8 };NumArray na = new NumArray(nums);na.update(0, 3);System.out.println(na.sumRange(1, 1));na.update(0, 1);System.out.println(na.sumRange(0, 1));na.update(1, -3);System.out.println(na.sumRange(0, 1));}}// Your NumArray object will be instantiated and called as such:// NumArray numArray = new NumArray(nums);// numArray.sumRange(0, 1);// numArray.update(1, 10);// numArray.sumRange(1, 2);</span>


0 0