面试题:查找最小的 K个元素-使用最大堆

1. import java.util.Arrays;
2. import java.util.Random;
3.
4.
5. public class MinKElement {
6.
7. /**
8. * 5.最小的 K 个元素
9. * I would like to use MaxHeap.
10. * using QuickSort is also OK
11. */
12. public static void main(String[] args) {
13. MinKElement mke=new MinKElement();
14. int[] a={1,2,3,4,5,6,7,8};
15. int k=4;
16. mke.disArrange(a);
17. System.out.println("after disarranging,the array a[]="+Arrays.toString(a));
18. mke.findKMin(a,k);
19.
20. }
21.
22. //rearrange the array.just for test. 随机的调换数组
23. public void disArrange(int[] a){
24. for(int i=0,len=a.length;i<len;i++){
25. Random random=new Random();
26. int j=random.nextInt(len);
27. swap(a,i,j);
28. }
29. }
30. public void findKMin(int[] a,int k){
31. int[] heap=a;//you can do this:int[] heap=new int[k].but that maybe space-cost
32.
33. //create MaxHeap of K elements.from the lastRootIndex to 0. 先建立 K 的最大堆,K 个
值,那么起始点为 K/2-1 
34. int rootIndex=k/2-1;
35. while(rootIndex>=0){
36. reheap(heap,rootIndex,k-1);
37. rootIndex--;
38. }
39. for(int i=k,len=heap.length;i<len;i++){ //建立好 K 的最大堆之后,循环,将 length-k 之
外的值不断的和最大值进行对比,小于最大值,就纳入堆中,调整堆的最大堆
40. if(heap[i]<heap[0]){
41. heap[0]=heap[i];
42. reheap(heap,0,k-1);
43. }
44. }
45. System.out.print("the K min elements=");
46. for(int i=0;i<k;i++){
47. System.out.print(heap[i]+",");
48. }
49. }
50.
51. //reheap:from root to lastIndex.
52. public void reheap(int[] heap,int rootIndex,int lastIndex){
53. int orphan=heap[rootIndex];
54. boolean done=false;
55. int leftIndex=rootIndex*2+1;
56. while(!done&&leftIndex<=lastIndex){
57. int largerIndex=leftIndex;
58. if(leftIndex+1<=lastIndex){
59. int rightIndex=leftIndex+1;
60. if(heap[rightIndex]>heap[leftIndex]){
61. largerIndex=rightIndex;
62. }
63. }
64. //Attention! should not use -->heap[root]<heap[largerIndex]<--.
65. //I spend time to find the problem....
66. if(orphan<heap[largerIndex]){
67. heap[rootIndex]=heap[largerIndex];
68. rootIndex=largerIndex;
69. leftIndex=rootIndex*2+1;
70. }else{
71. done=true;
72. }
73. }
74. heap[rootIndex]=orphan;
75.
76. }
77. public void swap(int[] a,int i,int j){
78. int temp=a[i];
79. a[i]=a[j];
80. a[j]=temp;
81. }
82. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EthanMilk

你的鼓励是我创作的最大动力谢谢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值