`
wx1569632409
  • 浏览: 100718 次
文章分类
社区版块
存档分类
最新评论

Lintcode247 Segment Tree Query II solution 题解

 
阅读更多

【题目描述】

For an array, we can build a Segment Tree for it, each node stores an extra attribute count to denote the number of elements in the the array which value is between interval start and end. (The array may not fully filled by elements)

Design a query method with three parameters root,start and end, find the number of elements in the in array's interval [start,end] by the given root of value Segment Tree.

Notice:It is much easier to understand this problem if you finished Segment Tree Build and Segment Tree Query first.

对于一个数组,我们可以对其建立一棵线段树, 每个结点存储一个额外的值count来代表这个结点所指代的数组区间内的元素个数. (数组中并不一定每个位置上都有元素)

实现一个query的方法,该方法接受三个参数root,start和end, 分别代表线段树的根节点和需要查询的区间,找到数组中在区间[start,end]内的元素个数。

【注】如果你完成了 Segment Tree Build 和 Segment Tree Query两道题,会更容易理解此题。

【题目链接】

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

【题目解析】

题目里的start end指的是数组的值的取值范围,count表示的是在这个取值范围之内有几个数字。

可以采用二分法解题。

如果root.start >= start && root.end <= end,  这就意味着这个root所包含的范围是我们要求解的一个范围的子范围,这个范围内的count值我们是要的,所以直接返回root。count

接下来进行二分。

mid = (start + end)/2;

如果mid 《start, 说明root节点的左半部分是不需要考虑的,因此调用 query(root.right, start, end);

如果 mid 》= end, 说明root节点的右侧的值全部比end要大,也不是我们需要考虑的范围,因此调用 query(root,left, start ,end)

最后,如果mid在start跟end之间,那么就需要分别统计 start~mid mid+1~ end范围的结果,然后加起来。

【参考答案】

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

转载于:https://my.oschina.net/u/3776581/blog/1619923

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics