使用PriorityQueue实现大小根堆

1.一个基于优先级堆的无界优先级队列。优先级队列的元素默认按照其自然顺序进行排序(即默认小根堆),大根堆需要通过构造方法重写Comparator接口的compare方法。
2.初始容量为11,线程不安全,线程安全的实现结构为PriorityBlockingQueue

3.小根堆的实现

public class findTopK {
   

    //找出前k个最大数,采用小顶堆实现
    public static int[] findKMax(int[] nums, int k) {
   
        PriorityQueue<Integer> pq = new PriorityQueue<>(k);//队列默认自然顺序排列,小顶堆,不必重写compare

        for (int num : nums) {
   
            if (pq.size() < k) {
   
                pq.offer(num);
            } else if (pq.peek() < num) {
   //如果堆顶元素 < 新数,则删除堆顶,加入新数入堆
                pq.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是将上面的大根堆实现改成小根堆的代码: ```cpp template <typename T> class PriorityQueue { public: // 构造函数 PriorityQueue() { // 初始化堆大小 capacity = 10; // 初始化堆数组 heap = new T[capacity]; // 初始化堆大小为0 size = 0; } // 析构函数 ~PriorityQueue() { delete[] heap; } // 入队 void push(const T& value) { // 如果堆已满,则进行扩容 if (size == capacity) { resize(); } // 将元素插入堆尾 heap[size++] = value; // 上浮操作 siftUp(size - 1); } // 出队 void pop() { // 如果堆为空,则直接返回 if (empty()) { return; } // 将堆尾元素移到堆顶 heap[0] = heap[--size]; // 下沉操作 siftDown(0); } // 获取队列大小 int size() const { return size; } // 判断队列是否为空 bool empty() const { return size == 0; } // 获取队头元素 T top() const { return heap[0]; } private: // 堆数组 T* heap; // 堆的大小 int size; // 堆的容量 int capacity; // 上浮操作 void siftUp(int index) { // 父节点的索引 int parent = (index - 1) / 2; // 当前节点比父节点小,则交换它们 while (index > 0 && heap[index] < heap[parent]) { std::swap(heap[index], heap[parent]); index = parent; parent = (index - 1) / 2; } } // 下沉操作 void siftDown(int index) { while (true) { // 左子节点的索引 int leftChild = index * 2 + 1; // 右子节点的索引 int rightChild = index * 2 + 2; // 用于比较的最小值索引 int minIndex = index; // 如果左子节点比当前节点小,则更新最小值索引 if (leftChild < size && heap[leftChild] < heap[minIndex]) { minIndex = leftChild; } // 如果右子节点比当前节点小,则更新最小值索引 if (rightChild < size && heap[rightChild] < heap[minIndex]) { minIndex = rightChild; } // 如果最小值索引不是当前节点,则交换它们,并继续下沉 if (minIndex != index) { std::swap(heap[index], heap[minIndex]); index = minIndex; } else { // 否则,已经满足堆的性质,退出循环 break; } } } // 扩容操作 void resize() { // 新容量为原来的两倍 capacity *= 2; // 新建一个更大的数组 T* newHeap = new T[capacity]; // 将原有元素复制到新数组中 for (int i = 0; i < size; i++) { newHeap[i] = heap[i]; } // 删除原有数组 delete[] heap; // 更新指针 heap = newHeap; } }; ``` 在这个实现中,我们将比较运算符由“>”改为“<”,同时将最大值的概念改为最小值的概念。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值