Top K是很常见的一种问题,是指在N个数的无序序列中找出最大的K个数,而其中的N往往都特别大,对于这种问题,最容易想到的办法当然就是先对其进行排序,然后直接取出最大的K个元素就行了,但是这种方法往往是不可靠的,不仅时间效率低而且空间开销大,排序是对所有数都要进行排序,而实际上,这类问题只关心最大的K个数,并不关心序列是否有序,因此,排序实际上是浪费了的很多资源都是没必要的。

海量数据 Top K 问题的解决方案

题目:

输入 n 个整数,找出其中最大的 k 个数。例如输入4、5、1、6、2、7、3、8 这8个数字,则最大的4个数字是5、6、7、8。

解法一:基于快排的O(n)的算法
如果基于数组的第 k 个数字来调整,使得比第 k 个数字小的所有数字都位于数组的左边,比第 k 个数字大的所有数字都位于数组的右边。这样调整之后,位于数组中左边的 k 个数字就是最小的 k 个数字(这 k 个数字不一定是排序的)。

  1. public class LeastK {
  2. public static void getLeastNumbers(int[] input, int[] output) {
  3. if (input == null || output == null || output.length <= 0 || input.length < output.length) {
  4. throw new IllegalArgumentException("Invalid args");
  5. }
  6. int start = 0;
  7. int end = input.length - 1;
  8. int index = partition(input, start, end); // 切分后左子数组的长度
  9. int target = output.length - 1; // K-1
  10.  
  11. // 若切分后左子数组长度不等于K
  12. while (index != target) { // 若切分后左子数组长度小于K,那么继续切分右子数组,否则继续切分左子数组
  13. if (index < target) {
  14. start = index + 1;
  15. } else {
  16. end = index - 1;
  17. }
  18. index = partition(input, start, end);
  19. }
  20.  
  21. System.arraycopy(input, 0, output, 0, output.length);
  22. }
  23.  
  24. private static int partition(int arr[], int left, int right) {
  25. int i = left;
  26. int j = right + 1;
  27. int pivot = arr[left];
  28. while (true) { // 找到左边大于pivot的数据,或者走到了最右边仍然没有找到比pivot大的数据
  29. while (i < right && arr[++i] < pivot) { // 求最大的k个数时,arr[++i] > pivot
  30. if (i == right) {
  31. break;
  32. }
  33. } // 找到右边小于pivot的数据,或者走到了最左边仍然没有找到比pivot小的数据
  34. while (j > left && arr[--j] > pivot) { // 求最大的k个数时,arr[--j] < pivot
  35. if (j == left) {
  36. break;
  37. }
  38. } // 左指针和右指针重叠或相遇,结束循环
  39. if (i >= j) {
  40. break;
  41. } // 交换左边大的和右边小的数据
  42. swap(arr, i, j);
  43. } // 此时的 a[j] <= pivot,交换之
  44. swap(arr, left, j);
  45. return j;
  46. }
  47.  
  48. private static void swap(int[] arr, int i, int j) {
  49. int tmp = arr[i];
  50. arr[i] = arr[j];
  51. arr[j] = tmp;
  52. }
  53.  
  54. }

采用上面的思路是有限制的,比如需要修改输入的数组,因为函数 Partition 会调整数组中的顺序,当然了,这个问题完全可以通过事先拷贝一份新数组来解决。值得说明的是,这种思路是不适合处理海量数据的。若是遇到海量数据求最小的 k 个数的问题,可以使用下面的解法。

解法二:最小堆法

利用最小堆的思想,先读取前k个元素,建立一个最小堆。然后将剩余的所有元素依次与堆顶元素进行比较,如果大于堆顶元素,则堆顶弹出,否则,压入下一个数组元素继续比较,只要维护大小为k的堆就可以了,此方法适合处理海量数据,时间复杂度为O(nlogk)。java的PriorityQueue可以实现最小堆。

  1. import java.util.Arrays;
  2. import java.util.PriorityQueue;
  3. import java.util.Random;
  4.  
  5. public class TopK {
  6.  
  7. public static void main(String[] args) {
  8. int number = 100000000;// 一亿个数
  9. int maxnum = 1000000000;// 随机数最大值
  10. int topnum = 100;// 取最大的多少个
  11.  
  12. int[] nums = new int[100000000];
  13. Random random = new Random();
  14. for (int i = 0; i < number; i++) {
  15. int s = Math.abs(random.nextInt(maxnum));
  16. nums[i] = s;
  17. }
  18.  
  19. Integer[] res = TopK.getLargestNumbers(nums, topnum);
  20. System.out.println(Arrays.toString(res));
  21.  
  22. }
  23.  
  24. public static Integer[] getLargestNumbers(int[] nums, int k) {
  25. PriorityQueue<Integer> minQueue = new PriorityQueue<>(k); // 默认自然排序
  26. for (int num : nums) {
  27. if (minQueue.size() < k || num > minQueue.peek()) { // peek():返回队列头部的值,也就是队列最小值
  28. // 插入元素
  29. minQueue.offer(num);
  30. }
  31. if (minQueue.size() > k) { // 删除队列头部
  32. minQueue.poll();
  33. }
  34. }
  35. return minQueue.toArray(new Integer[0]);
  36. }
  37.  
  38. }

也可以将上述代码改为手动实现最小堆的方式,代码如下:

  1. import java.util.Arrays;
  2. import java.util.Date;
  3. import java.util.Random;
  4. public class Top100 {
  5. public static void main(String[] args) {
  6. find();
  7. }
  8. public static void find( ) {//
  9. int number = 100000000;// 一亿个数
  10. int maxnum = 1000000000;// 随机数最大值
  11. int i = 0;
  12. int topnum = 100;// 取最大的多少个
  13. Date startTime = new Date();
  14. Random random = new Random();
  15. int[] top = new int[topnum];
  16. for (i = 0; i < topnum; i++) {
  17. top[i] = Math.abs(random.nextInt(maxnum));//设置为随机数
  18. // top[i] = getNum(i);
  19. }
  20. buildHeap(top, 0, top.length);// 构建最小堆, top[0]为最小元素
  21. for (i = topnum; i < number; i++) {
  22. int currentNumber2 = Math.abs(random.nextInt(maxnum));//设置为随机数
  23. // int currentNumber2 = getNum(i);
  24. // 大于 top[0]则交换currentNumber2 重构最小堆
  25. if (top[0] < currentNumber2) {
  26. top[0] = currentNumber2;
  27. shift(top, 0, top.length, 0); // 构建最小堆 top[0]为最小元素
  28. }
  29. }
  30. System.out.println(Arrays.toString(top));
  31. sort(top);
  32. System.out.println(Arrays.toString(top));
  33. Date endTime = new Date();
  34. System.out.println("用了"+(endTime.getTime() - startTime.getTime())+"毫秒");
  35. }
  36. public static int getNum(int i){
  37. return i;
  38. }
  39. //构造排序数组
  40. public static void buildHeap(int[] array, int from, int len) {
  41. int pos = (len - 1) / 2;
  42. for (int i = pos; i >= 0; i--) {
  43. shift(array, from, len, i);
  44. }
  45. }
  46. /**
  47. * @param array top数组
  48. * @param from 开始
  49. * @param len 数组长度
  50. * @param pos 当前节点index
  51. * */
  52. public static void shift(int[] array, int from, int len, int pos) {
  53. // 保存该节点的值
  54. int tmp = array[from + pos];
  55. int index = pos * 2 + 1;// 得到当前pos节点的左节点
  56. while (index < len)// 存在左节点
  57. {
  58. if (index + 1 < len
  59. && array[from + index] > array[from + index + 1])// 如果存在右节点
  60. {
  61. // 如果右边节点比左边节点小,就和右边的比较
  62. index += 1;
  63. }
  64. if (tmp > array[from + index]) {
  65. array[from + pos] = array[from + index];
  66. pos = index;
  67. index = pos * 2 + 1;
  68. } else {
  69. break;
  70. }
  71. }
  72. // 最终全部置换完毕后 ,把临时变量赋给最后的节点
  73. array[from + pos] = tmp;
  74. }
  75. public static void sort(int[] array){
  76. for(int i = 0; i < array.length - 1; i++){
  77. //当前值当作最小值
  78. int min = array[i];
  79. for(int j = i+1; j < array.length; j++){
  80. if(min>array[j]){
  81. //如果后面有比min值还小的就交换
  82. min = array[j];
  83. array[j] = array[i];
  84. array[i] = min;
  85. }
  86. }
  87. }
  88. }
  89. }

若是遇到此类求海量数据中最小的 k 个数的问题,只需改用最大堆即可。构建最大堆,需要重写compare方法。

  1. import java.util.Arrays;
  2. import java.util.Comparator;
  3. import java.util.PriorityQueue;
  4. import java.util.Random;
  5.  
  6. public class TopKK {
  7.  
  8. public static void main(String[] args) {
  9. int number = 100000000;// 一亿个数
  10. int maxnum = 1000000000;// 随机数最大值
  11. int topnum = 100;// 取最大的多少个
  12.  
  13. int[] nums = new int[100000000];
  14. Random random = new Random();
  15. for (int i = 0; i < number; i++) {
  16. int s = Math.abs(random.nextInt(maxnum));
  17. nums[i] = s;
  18. }
  19.  
  20. Integer[] res = TopKK.getLeastNumbers(nums, topnum);
  21. System.out.println(Arrays.toString(res));
  22.  
  23. }
  24.  
  25. public static Integer[] getLeastNumbers(int[] nums, int k) { // 默认自然排序,需手动转为降序
  26. PriorityQueue<Integer> maxQueue = new PriorityQueue<>(k, new Comparator<Integer>() {
  27. @Override
  28. public int compare(Integer o1, Integer o2) {
  29. //if (o1 > o2) {
  30. // return -1;
  31. //} else if (o1 < o2) {
  32. // return 1;
  33. //}
  34. //return 0;
  35. return o2.compareTo(o1);
  36. }
  37. });
  38. for (int num : nums) {
  39. if (maxQueue.size() < k || num < maxQueue.peek()) { // peek():返回队列头部的值,也就是队列最大值
  40. // 插入元素
  41. maxQueue.offer(num);
  42. }
  43. if (maxQueue.size() > k) { // 删除队列头部
  44. maxQueue.poll();
  45. }
  46. }
  47. return maxQueue.toArray(new Integer[0]);
  48. }
  49.  
  50. }

本文已通过「原本」原创作品认证,转载请注明文章出处及链接。

算法最后更新:2022-11-7
夏日阳光
  • 本文由 夏日阳光 发表于 2019年10月16日
  • 本文为夏日阳光原创文章,转载请务必保留本文链接:https://www.pieruo.com/117.html
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定

拖动滑块以完成验证
加载中...