307. Range Sum Query - Mutable

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

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.


线段树模板题。

public class NumArray {

    SegmentTree2 segtree;
	int len;
	
    public NumArray(int[] nums)
    {
        len=nums.length;
        segtree=new SegmentTree2(len);
        segtree.build(1, len, 1, nums);
    }

    void update(int i, int val)
    {
        segtree.update(i+1, val, 1, len, 1);
    }

    public int sumRange(int i, int j)
    {
        return (int) segtree.query(i+1, j+1, 1, len, 1);
    }
}

class SegmentTree2
{
	private long[] ele;
	int cnt=0;

	public SegmentTree2(int maxn)
	{
		ele = new long[maxn << 2];
	}



	public void build(int l, int r, int rt,int[] arr)
	{
		if(arr.length<1)
			return ;
		
		if (l == r)
		{
			ele[rt] = arr[cnt++];
			return;
		}
		
		int m = (l + r) >> 1;
		build(l, m, rt << 1,arr);
		build(m + 1, r, rt << 1 | 1,arr);
		PushUP(rt);
	}

	private void PushUP(int rt)
	{
		ele[rt] = ele[rt << 1] + ele[rt << 1 | 1];
	}

	public void update(int p, int sc, int l, int r, int rt)
	{
		if(ele.length<1)
			return ;
		
		if (l == r)
		{
			ele[rt] = sc;
			return;
		}
		int m = (l + r) >> 1;
		if (p <= m)
			update(p, sc, l, m, rt << 1);
		else
		{
			update(p, sc, m + 1, r, rt << 1 | 1);
		}
		PushUP(rt);
	}

	public long query(int L, int R, int l, int r, int rt)
	{
		if(ele.length<1)
			return 0;
		
		if (L <= l && r <= R)
			return ele[rt];
		int m = (l + r) >> 1;
		long ret = 0;
		if (L <= m)
			ret += query(L, R, l, m, rt << 1);
		if (R > m)
			ret += query(L, R, m + 1, r, rt << 1 | 1);
		return ret;
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值