【Lintcode】203. Segment Tree Modify

题目地址:

https://www.lintcode.com/problem/segment-tree-modify/description

给定一个存一个数组的区间最大值的线段树,现在要将数组中某个位置 i i i的数改为 v v v,要求返回数组改变后的对应的线段树。

思路是递归。先将 i i i这个位置对应的线段树中的叶子节点更新,然后递归回去的时候把父节点存储的最大值更新即可。代码如下:

public class Solution {
    /**
     * @param root: The root of segment tree.
     * @param index: index.
     * @param value: value
     * @return: nothing
     */
    public void modify(SegmentTreeNode root, int index, int value) {
        // write your code here
        // 如果走到了对应的叶子,则更新值
        if (root.start == root.end && root.start == index) {
            root.max = value;
            return;
        }
        // 求区间中点
        int mid = root.start + (root.end - root.start >> 1);
        
		// 如果要更新的值的下标在左半区间,那就向左子树递归
        if (index <= mid) {
            modify(root.left, index, value);
        }

		if (index > mid) {
            modify(root.right, index, value);
        }
        
        // 更新根节点
        root.max = Math.max(root.left.max, root.right.max);
    }
}

class SegmentTreeNode {
    int start, end, max;
    SegmentTreeNode left, right;
    
    public SegmentTreeNode(int start, int end, int max) {
        this.start = start;
        this.end = end;
        this.max = max;
    }
}

时空复杂度 O ( log ⁡ n ) O(\log n) O(logn) n n n是数组长度。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值