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. Have you met this question in a real interview? Yes
Example
For array [1,2,7,8,5], and queries [1,8,5], return [0,4,2] Note
We suggest you finish problem Segment Tree Build and Segment Tree Query II first. Challenge
Could you use three ways to do it. Just loop
Sort and binary search
Build Segment Tree and Search.
跟count of Range Sum很像, 维护一个leftsize, 记录左子树节点个数, 为方便起见,再维护一个count,记录重复节点
construct BST, time complexity: O(N) construct tree + O(logN) queries
public class Solution {
/**
* @param A: An integer array
* @return: The number of element in the array that
* are smaller that the given integer
*/ 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;
}
} 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++) {
insert(root, A[i]);
}
for (int query : queries) {
res.add(queryTree(root, query));
}
return res;
} public TreeNode insert(TreeNode cur, int value) {
if (cur == null) {
cur = new TreeNode(value);
}
else if (cur.value == value) {
cur.count++;
}
else if (cur.value > value) {
cur.leftsize++;
cur.left = insert(cur.left, value);
}
else {
cur.right = insert(cur.right, value);
}
return cur;
} public int queryTree(TreeNode cur, int target) {
if (cur == null) return 0;
else if (cur.value == target) return cur.leftsize;
else if (cur.value > target) {
return queryTree(cur.left, target);
}
else {
return cur.leftsize + cur.count + queryTree(cur.right, target);
}
}
}