0
1
TOP N的处理方式
top n 如果是直接针对的可排序的数据集合,并且不需要二次计算的话,则全局的top n就是可以分散到局部的top n再聚合。
如果数据集不是可排序的,并且也需要进行二次计算,类似按某个统计指标来取 top n,可能就不能直接用局部的top n来并行计算。
抽象的来说,同一个top n算法要适应不同的动态数据分布是很难的,top n不是处理特定的数据分布的,而是要通用型的
top n或许可以从满足充分必要条件来做一些反向推导,得到一些限制条件,从而过滤掉数据,让数据量减少,逐步收敛于某个范围。
如果采用过滤数据量的话,需要借助一些统计的指标,如:记录的总数等。
top N一般的做法就是将数据先局部处理,例如:计算单词的出现的个数 top N,可先局部统计每个区域中的单词的次数,重新写入临时文件,后续再进行数据的合并。
top N还有一种做法就是将数据按照key进行独立计算,区域是按照key进行分区,譬如:按照单词来直接得到它的统计总数,这个类似storm的处理方式。
0
2
案例实现
使用快排法,查找最小的n个数。
public static void main(String[] args) {
int [] arr = {2, 6, 3, 8, 9, 1, 16, 18, 0, 4};
int N = 3;
getTopNMinBySort(arr, 0, arr.length - 1, N);
for (int i = 0; i < N; i++) {
System.out.print(arr[i] + " ");
}
}
private static int partion(int [] arr, int first, int end) {
int i = first;
int main = arr[end];
for (int j = first; j < end; j++) {
if (arr[j] < main) {
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
i++;
}
}
arr[end] = arr[i];
arr[i] = main;
return i;
}
private static void getTopNMinBySort(int [] arr, int first, int end, int n) {
if (first < end) {
int partionIndex = partion(arr, first, end);
if (partionIndex == n - 1) {
return;
} else if (partionIndex > n - 1) {
getTopNMinBySort(arr, first, partionIndex - 1, n);
} else {
getTopNMinBySort(arr, partionIndex + 1, end, n);
}
}
}