模拟优先队列操作——堆实现

 1 public class Solution {
 2     /**
 3      * @param nums: an integer array
 4      * @param k: An integer
 5      * @return: the top k largest numbers in array
 6      */
 7     public int[] topk(int[] nums, int k) {
 8         // write your code here
 9         PriorityQueue pq = new PriorityQueue();
10         for(int i = 0; i < nums.length; i++){
11             pq.push(nums[i]);
12             if(pq.size() > k) pq.pop();
13         }
14         int[] ans = new int[k];
15         for(int i = k - 1; i >= 0; i--){
16             ans[i] = pq.top();
17             pq.pop();
18         }
19         return ans;
20     }
21 }
22 class PriorityQueue{
23     ArrayList<Integer> heap = new ArrayList<Integer>();
24     void push(int num){
25         heap.add(num);
26         int index = heap.size() - 1;
27         while(index > 0){
28             int fatherIndex = (index - 1) / 2;
29             if(heap.get(fatherIndex) < heap.get(index)) break;
30             int tempFather = heap.get(fatherIndex);
31             int tempSon = heap.get(index);
32             heap.set(fatherIndex, tempSon);
33             heap.set(index, tempFather);
34         index = fatherIndex;
35         }
36     }
37     int top(){
38         return heap.get(0);
39     }
40     void pop(){
41         heap.set(0, heap.get(heap.size() - 1));
42         heap.remove(heap.size() - 1);
43         int index = 0;
44         while(index < heap.size()){
45             int index1 = (index + 1) * 2 - 1;
46             int index2 = (index + 1) * 2;
47             int minIndex = index;
48             if(index1 < heap.size() && heap.get(index1) < heap.get(minIndex)) minIndex = index1;
49             if(index2 < heap.size() && heap.get(index2) < heap.get(minIndex)) minIndex = index2;
50             if(minIndex == index) break;
51             int tempFather = heap.get(index);
52             int tempSon = heap.get(minIndex);
53             heap.set(index, tempSon);
54             heap.set(minIndex, tempFather);
55             index = minIndex;
56         } 
57     }
58     int size(){
59         return heap.size();
60     }
61 }

 

转载于:https://www.cnblogs.com/liqiniuniu/p/10622411.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值