Java数据结构 -------PriorityQueue详解

PriorityQueue —优先级链表

可以理解为不去重的TreeSet

  • PriorityQueue 一个基于优先级的无界优先级队列。优先级队列的元素按照其自然顺序进行排序,或者根据构造队列时提供的 Comparator 进行排序。
  • 该队列不允许使用 null 元素也不允许插入不可比较的对象(没有实现Comparable接口的对象)。
  • PriorityQueue 队列的头指排序规则最小那哥元素。如果多个元素都是最小值则随机选一个。
  • PriorityQueue 是一个无界队列,但是初始的容量(实际是一个Object[]),随着不断向优先级队列添加元素,其容量会自动扩容,无需指定容量增加策略的细节。

在这里插入图片描述

合并k个生序链表

import java.util.*;
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode  pomml =new ListNode(0);
        ListNode  result=pomml;
        //新建PriorityQueue 并且添加比较器
        PriorityQueue<ListNode> pq=new PriorityQueue<>((l1,l2)->{return l1.val-l2.val;});
        //添加各个链表的头,并且不添加null(priorityQueue添加null会报错)
        for (ListNode list : lists) {
            if(list!=null) pq.add(list);
        }
        while (!pq.isEmpty()){
        	//弹出值最小链表并且后移一位,并把最小链表的下一个节点加入priorityQueue
            ListNode first = pq.poll();
            pomml.next=first;
            pomml=pomml.next;
            ListNode listNode=first.next;
            if(listNode!=null) pq.add(listNode);
        }
        return result.next;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用优先队列求解 0-1 背包问题的 C 语言代码: ```c #include <stdio.h> #include <stdlib.h> #define MAX_N 1000 #define MAX_W 10000 // 物品结构体 typedef struct Item { int w; // 重量 int v; // 价值 } Item; // 优先队列结构体 typedef struct PriorityQueue { int size; // 队列大小 int items[MAX_N+1]; // 队列元素数组,下标从1开始 } PriorityQueue; // 优先队列相关操作 PriorityQueue* createPriorityQueue() { PriorityQueue* q = (PriorityQueue*)malloc(sizeof(PriorityQueue)); q->size = 0; return q; } void push(PriorityQueue* q, int x) { int i = ++q->size; while (i > 1 && q->items[i/2] < x) { q->items[i] = q->items[i/2]; i /= 2; } q->items[i] = x; } int pop(PriorityQueue* q) { int ret = q->items[1]; int x = q->items[q->size--]; int i = 1, j = 2; while (j <= q->size) { if (j < q->size && q->items[j] < q->items[j+1]) j++; if (q->items[j] <= x) break; q->items[i] = q->items[j]; i = j; j = i*2; } q->items[i] = x; return ret; } int empty(PriorityQueue* q) { return q->size == 0; } // 0-1背包问题求解函数 int knapsack(int n, int w, Item* items) { PriorityQueue* q = createPriorityQueue(); push(q, 0); // 边界条件 int i, j; for (i = 0; i < n; i++) { for (j = w-items[i].w; j >= 0; j--) { if (!empty(q)) { int k = pop(q); if (k+j+items[i].w <= w) { push(q, k+j+items[i].w); } } } } int ans = pop(q); free(q); return ans; } // 测试代码 int main() { int n = 3, w = 7; Item items[n] = {{3, 2}, {4, 3}, {2, 4}}; int ans = knapsack(n, w, items); printf("ans = %d\n", ans); return 0; } ``` 该算法的时间复杂度为 O(n*w*log(n*w)),其中 n 表示物品数量,w 表示背包容量。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值