统计比给定整数小的数的个数
题目
给定一个整数数组 (下标由 0 到 n-1,其中 n 表示数组的规模,数值范围由 0 到 10000),以及一个 查询列表。对于每一个查询,将会给你一个整数,请你返回该数组中小于给定整数的元素的数量。
注意事项
在做此题前,最好先完成 线段树的构造 and 线段树查询 II 这两道题目。样例
对于数组 [1,2,7,8,5] ,查询 [1,8,5],返回 [0,4,2]
挑战
可否用一下三种方法完成以上题目。
1.仅用循环方法
2.分类搜索 和 二进制搜索
3.构建 线段树 和 搜索题解
public class Solution {
class SegmentTreeNode
{
public int start, end;
public int 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;
}
}
SegmentTreeNode root;
public ArrayList<Integer> countOfSmallerNumber(int[] A, int[] queries) {
root = build(0, 10000);
ArrayList<Integer> ans = new ArrayList<Integer>();
int res;
for(int i = 0; i < A.length; i++)
{
modifySegmentTree(root, A[i], 1);
}
for(int i = 0; i < queries.length; i++)
{
res = queries[i] > 0 ? querySegmentTree(root, 0, queries[i] - 1) : 0;
ans.add(res);
}
return ans;
}
public SegmentTreeNode build(int start, int end)
{
SegmentTreeNode root = new SegmentTreeNode(start, end, 0);
if (start == end)
{
root.count = 0;
return root;
}
int mid = (start + end) / 2;
root.left = build(start, mid);
root.right = build(mid+1, end);
return root;
}
public int querySegmentTree(SegmentTreeNode root, int start, int end)
{
if(start == root.start && root.end == end)
{
return root.count;
}
int mid = (root.start + root.end)/2;
int leftcount = 0;
int rightcount = 0;
if(start <= mid)
{
leftcount = querySegmentTree(root.left, start, Math.min(mid,end));
}
if(mid < end)
{
rightcount = querySegmentTree(root.right, start <= mid ? mid+1 : start, end);
}
return leftcount + rightcount;
}
public void modifySegmentTree(SegmentTreeNode root, int index, int value)
{
if(root.start == index && root.end == index)
{
root.count += value;
return;
}
int mid = (root.start + root.end) / 2;
if(root.start <= index && index <=mid)
{
modifySegmentTree(root.left, index, value);
}
if(mid < index && index <= root.end)
{
modifySegmentTree(root.right, index, value);
}
root.count = root.left.count + root.right.count;
}
}
Last Update 2016.11.5
本文介绍了一种使用线段树解决特定查询问题的方法。通过构建线段树,并实现修改和查询操作,可以高效地统计一个整数数组中小于给定阈值的元素数量。文章提供了一个具体的例子和完整的Java实现代码。
3万+

被折叠的 条评论
为什么被折叠?



