lintcode-medium-Segment Tree Query II
2016-04-05 17:58
399 查看
For an array, we can build a
Design a
Example
For array
SegmentTreefor it, each node stores an extra attribute
countto 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
querymethod with three parameters
root,
startand
end, find the number of elements in the in array's interval [start, end] by the given root of value SegmentTree.
Example
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
/** * Definition of SegmentTreeNode: * public class SegmentTreeNode { * public int start, end, count; * public SegmentTreeNode left, right; * public SegmentTreeNode(int start, int end, int count) { * this.start = start; * this.end = end; * this.count = count; * this.left = this.right = null; * } * } */ public class Solution { /** *@param root, start, end: The root of segment tree and * an segment / interval *@return: The count number in the interval [start, end] */ public int query(SegmentTreeNode root, int start, int end) { // write your code here if(root == null) return 0; if(start > end || root.end < start || root.start > end) return 0; if(root.start == start && root.end == end){ return root.count; } int leftcount = 0; int rightcount = 0; int mid = root.start + (root.end - root.start) / 2; if(start <= mid){ if(end <= mid){ leftcount = query(root.left, Math.max(start, root.start), end); } else{ leftcount = query(root.left, Math.max(start, root.start), mid); } } if(end > mid){ if(start > mid){ rightcount = query(root.right, start, Math.min(end, root.end)); } else{ rightcount = query(root.right, mid + 1, Math.min(end, root.end)); } } return leftcount + rightcount; } }
相关文章推荐
- 【iOS】使用UIView绘制本地验证码
- lintcode-medium-Segment Tree Query
- What's the difference between all the Selection Segues?
- 【iOS】UILabel多行文本的高度计算
- lintcode-medium-Segment Tree Build II
- lintcode-medium-Segment Tree Build
- Material Design UI Widgets —— Palette 调色板
- 大作业关于(“有爱”youi)的简介
- mysql5中大数据错误:Packet for query is too large (1117260 > 1048576). You can change this value on the ser
- 将UIDatePicker的日期显示为数字和中文
- Material Design UI Widgets —— CardView 卡片视图
- CodeForces 618B-Guess the Permutation【搜索】
- NSURLConnection的sendAsynchronousRequest
- iOS开发学习笔记——控制器(UIViewController)
- HDU 1242 Rescue dfs
- [ios] dispatch_get_main_queue 的同步异步问题
- Meterial Design UI Widgets —— RecyclerView 循环视图
- Android4.4 Systemui状态栏状态图标更新流程分析
- LeetCode 63 - Unique Paths II
- UITableView的section header view悬停的方法