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.
Example
Example 1:
Input: array =[1,2,7,8,5] queries =[1,8,5]
Output:[0,4,2]
Example 2:
Input: array =[3,4,5,8] queries =[2,4]
Output:[0,1]
Challenge
Could you use three ways to do it.
- Just loop
- Sort and binary search
- Build Segment Tree and Search.
import java.util.*;
public class Solution {
/**
* @param A: An integer array
* @param queries: The query list
* @return: The number of element in the array that are smaller that the given integer
*/
public List<Integer> countOfSmallerNumber(int[] A, int[] queries) {
// write your code here
List<Integer> returnvalue = new ArrayList<Integer>();
Hashtable<Integer, Integer> existTable = new Hashtable<Integer,Integer>();
for(int i =0;i<queries.length;i++){
int count = 0;
int temp = queries[i];
if(existTable.containsKey(temp)){
returnvalue.add(existTable.get(temp));
}
else{
for(int j =0; j<A.length;j++){
if(A[j]<temp){
count++;
}
}
returnvalue.add(count);
}
}
return returnvalue;
}
}