LeetCode Range Sum Query - Mutable

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) -> 9
update(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);
			else
				update(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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值