Give you an integer array (index from 0 to n-1, where n is the size of this array, value from 0 to 10000) and an query list. For each query, give you an integer, return the number of element in the array that are smaller than the given integer.
Notice
We suggest you finish problem Segment Tree Build and Segment Tree Query II first.
Example
For array [1,2,7,8,5], and queries [1,8,5], return [0,4,2]
public class Solution {
class TreeNode {
int value;
int count;
int leftsize;
TreeNode left;
TreeNode right;
public TreeNode(int value) {
this.value = value;
this.count = 1;
this.left = null;
this.right = null;
this.leftsize = 0;
}
}
/**
* @param A: An integer array
* @return: The number of element in the array that
* are smaller that the given integer
*/
public ArrayList<Integer> countOfSmallerNumber(int[] A, int[] queries) {
// write your code here
ArrayList<Integer> res = new ArrayList<Integer>();
if (A == null || queries == null || queries.length == 0)
return res;
if (A.length == 0) {
for (int i=0; i<queries.length; i++) {
res.add(0);
}
return res;
}
TreeNode root = new TreeNode(A[0]);
for (int i=1; i<A.length; i++) {
insertTree(root, A[i]);
}
for (int query : queries) {
res.add(queryTree(root, query));
}
return res;
}
public TreeNode insertTree(TreeNode curNode, int value) {
if (curNode == null) {
return new TreeNode(value);
}
if (curNode.value == value) {
curNode.count++;
}
else if (value < curNode.value) {
curNode.leftsize++;
curNode.left = insertTree(curNode.left, value);
}
else {
curNode.right = insertTree(curNode.right, value);
}
return curNode;
}
public int queryTree(TreeNode curNode, int target) {
if (curNode == null) {
return 0;
}
if (curNode.value == target) {
return curNode.leftsize;
}
else if (target < curNode.value) {
return queryTree(curNode.left, target);
}
else {
return curNode.leftsize + curNode.count + queryTree(curNode.right, target);
}
}
}

本文介绍了一种使用二叉搜索树的方法来解决一个特定的问题:对于给定的整数数组及一系列查询,如何高效地计算出数组中每个查询值之下有多少个元素。通过构建树节点并维护每个节点的左子树大小,可以快速响应查询。
1245

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



