力扣: 303. 区域和检索 - 数组不可变


/**
 * @author xnl
 * @Description:
 * @date: 2022/6/21   21:41
 */
public class Solution {
    public static void main(String[] args) {
        int[] arr = {-2, 0, 3, -5, 2, -1};
        NumArray numArray = new NumArray(arr);
        System.out.println(numArray.sumRange(0 ,2));
    }


}


class NumArray {

    int[] tree;
    int[] data;
    public NumArray(int[] nums) {
        this.data = nums;
        this.tree = new int[nums.length * 4];
        buildTree(0, 0, data.length - 1);
    }

    private void buildTree(int treeIndex,  int l, int r){
        if (l == r){
            tree[treeIndex] = data[l];
            return;
        }
        int mid = l + (r - l) / 2;
        int left = treeIndex * 2 + 1;
        int right = treeIndex * 2 + 2;
        buildTree(left, l ,mid);
        buildTree(right, mid + 1, r);
        tree[treeIndex] = tree[left] + tree[right];
    }

    private int query(int treeIndex, int l, int r, int queryL, int queryR){
        if (l == queryL && r == queryR ){
            return tree[treeIndex];
        }
        int mid = l + (r - l) / 2;
        int left = treeIndex * 2 + 1;
        int right = treeIndex * 2 + 2;
        // 在左边界大于中间节点,往右边查找
        if (queryL > mid){
            return query(right, mid + 1, r, queryL, queryR);
        }
        if (queryR <= mid){
            return query(left, l, mid, queryL, queryR);
        }
        int leftResult = query(left, l ,mid, queryL, mid);
        int rightResult = query(right, mid + 1, r, mid + 1, queryR);
        return  leftResult + rightResult;
    }

    public int sumRange(int left, int right) {
        return query(0, 0, data.length - 1, left, right);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值