#247 Segment Tree Query II
来源:互联网 发布:手机管理淘宝店铺 编辑:程序博客网 时间:2024/05/29 17:50
题目描述:
For an array, we can build a SegmentTree
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 SegmentTree.
Notice
It is much easier to understand this problem if you finished Segment Tree Buildand Segment Tree Query first.
For array [0, 2, 3]
, the corresponding value Segment Tree is:
[0, 3, count=3] / \ [0,1,count=1] [2,3,count=2] / \ / \ [0,0,count=1] [1,1,count=0] [2,2,count=1], [3,3,count=1]
query(1, 1)
, return 0
query(1, 2)
, return 1
query(2, 3)
, return 2
query(0, 2)
, return 2
这题和#202一样,只不过max改成了count,就是一个recursion的思路。
Mycode(AC = 859ms):
/** * Definition of SegmentTreeNode: * class SegmentTreeNode { * public: * int start, end, count; * SegmentTreeNode *left, *right; * SegmentTreeNode(int start, int end, int count) { * this->start = start; * this->end = end; * this->count = count; * this->left = this->right = NULL; * } * } */class Solution {public: /** *@param root, start, end: The root of segment tree and * an segment / interval *@return: The count number in the interval [start, end] */ int query(SegmentTreeNode *root, int start, int end) { // write your code here if (root == NULL || start > end) { return 0; } else if (root->start == start && root->end == end) { return root->count; } else { int left_count = query(root->left, max(start, root->start), min(end, (root->start + root->end) / 2)); int right_count = query(root->right, max(start, (root->start + root->end) / 2 + 1), min(end, root->end)); return left_count + right_count; } }};
- #247 Segment Tree Query II
- Segment Tree Query II
- [Lintcode]Segment Tree Query II
- Lintcode - Segment Tree Query
- #202 Segment Tree Query
- Segment Tree Query
- Segment Tree Build II
- 247.Segment Tree Query II-线段树查询 II(中等题)
- #439 Segment Tree Build II
- *[Lintcode]Segment Tree Build II
- Query on a tree II
- [LintCode]Segment Tree Query 线段树的查询
- (LeetCode 307) Range Sum Query - Mutable(Segment Tree)
- lintcode segment-tree-query 线段树的查询
- leetcode: Segment Tree:Range Sum Query - Mutable(307)
- SPOJ913. Query on a tree II
- Spoj Query on a tree II (LCA)
- SPOJ PT07J Query on a tree II
- 【c语言】 计算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值。
- Forfiles命令详解
- 利用Spark解析Tomcat日志,并将统计结果存入Mysql数据库
- 【c语言】       小游戏——猜字游戏
- 【c语言】 模拟实现printf,要求功能: my_printf("dc\ts\ndc\ndc\ts!", ...)
- #247 Segment Tree Query II
- 【c语言】 编写一个函数reverse_string(char * string)(递归实现)
- 【顺序表】 c语言的顺序表
- 【动态顺序表】 c语言的动态顺序表
- 【单链表】 c语言的单链表
- 【面试题】 单链表的热点面试题(1 )
- 2016 年全国房价会呈什么趋势?
- 【linux】浅谈Linux下的 find 指令
- 【Linux】Centos下的"vim"的配置