Lintcode202 Segment Tree Query solution 题解

【题目描述】

 

 

For an integer array (index from 0 to n-1, where n is the size of this array), in the corresponding Segment Tree, each node stores an extra attribute max to denote the maximum number in the interval of the array (index from start to end).

对于一个有n个数的整数数组,在对应的线段树中, 根节点所代表的区间为0-n-1, 每个节点有一个额外的属性max,值为该节点所代表的数组区间start到end内的最大值。

为Segment Tree设计一个query的方法,接受3个参数root,start和end,线段树root所代表的数组中子区间[start, end]内的最大值。

【注】在做此题之前,请先完成线段树构造这道题目。

【题目链接】

www.lintcode.com/en/problem/segment-tree-query/

【题目解析】

这应该是Range Query的经典题目之一了。

此题可用Segment Tree来做的。 Segment Tree线段树每一个节点都是一段线段,有start和end,然后还可以有其他的值,比如区间和sum,区间最大值max,区间最小值min。我们可以用自底向上构建二叉树的方式构建Segment Tree,这个过程也有点类似于Bottom-up的merge sort,思想也是Divide and Conquer。完毕之后就可以在O(logn)的时间update,或者得到range Sum。

【参考答案】

www.jiuzhang.com/solutions/segment-tree-query/



作者:程风破浪会有时
链接:https://www.jianshu.com/p/28f787bab2cc
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @ 2018-02-09 23:32  admondguo  阅读(98)  评论(0编辑  收藏  举报