对于一个数组,我们可以对其建立一棵 线段树
, 每个结点存储一个额外的值 count
来代表这个结点所指代的数组区间内的元素个数. (数组中并不一定每个位置上都有元素)
实现一个 query
的方法,该方法接受三个参数 root
, start
和 end
, 分别代表线段树的根节点和需要查询的区间,找到数组中在区间[start, end]内的元素个数。
/**
* 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) {
if(root==NULL||start>end||start>root->end||end<root->start) return 0;
int mid=root->start+(root->end - root->start)/2;
if(start==root->start&&end==root->end) return root->count;
if(root->start==root->end) return root->count;
if(start>mid) return query(root->right,start,end);
if(end<=mid) return query(root->left,start,end);
return query(root->left,start,mid)+query(root->right,mid+1,end);
}
};