给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

答案1(参数是数组):

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length == 0) {
return null;
}
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
//后大前小
PriorityQueue<ListNode> pq = new PriorityQueue<>((o1, o2) -> o1.val - o2.val);
for(ListNode list : lists) {
if(list == null) {
continue;
}
pq.add(list);
}
while(!pq.isEmpty()) {
ListNode next = pq.poll();
cur.next = next;
cur = cur.next;
if(next.next != null) {
pq.add(next.next);
}
}
return dummy.next;
}
}

答案2:(参数是ArrayList)

import java.util.*;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
ListNode res = new ListNode(0);
ListNode cur = res;
PriorityQueue<ListNode> queue =
new PriorityQueue<>((o1, o2) -> o1.val - o2.val);
for(ListNode list : lists) {
if(list != null) {
queue.add(list);
}
}
while(!queue.isEmpty()) {
ListNode node = queue.poll();
if(node == null) {
continue;
}
cur.next = node;
cur = cur.next;
if(node.next != null) {
queue.offer(node.next);
}
}
return res.next;
}
}

自己方法:(超时)

import java.util.*;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
//使用优先队列(小根堆)
PriorityQueue<ListNode> queue =
new PriorityQueue<>((o1, o2) -> o1.val - o2.val);
ListNode res = new ListNode(0);
ListNode cur = res;
Iterator<ListNode> iter = lists.iterator();
while(iter.hasNext()) {
ListNode list = iter.next();
while(list != null) {
queue.add(list);
list = list.next;
}
}
while(!queue.isEmpty()) {
cur.next = queue.poll();
cur = cur.next;
}
return res.next;
}
}

最新文章

  1. LNMP环境搭建完整步骤
  2. 一个简单的游戏开发框架(四.舞台Stage)
  3. Linux学习笔记(18) Shell编程之流程控制
  4. Lua数据结构
  5. python函数应用
  6. Java虚拟机内存模型及垃圾回收监控调优
  7. oracle连接总结(内连接、外连接、自然连接,交叉连接,自连接)
  8. JAVA三大特性之多态
  9. js监听input等表单输入框的变化事件oninput
  10. CSDN博客导出工具 Mac By Swift
  11. J2那几个E和Web基础
  12. TCP/IP协议栈(三)——linux 向下的报文处理
  13. 安装新的int 9中断例程2
  14. MyISAM和InnoDB的索引实现
  15. C#遍历枚举中所有值
  16. js获取地址栏上参数的值
  17. C语言第八讲,指针*
  18. React项目中使用Mobx状态管理(二)
  19. StringBuffer 和 StringBuilder 类
  20. myeclipse 代码提示

热门文章

  1. Logstash:使用ELK堆栈进行API分析
  2. 延申三大问题中的第一个问题处理---原先shell脚本中启动jar文件命令的配置,附加参数等
  3. Docker 部署 Confluence(破解版)
  4. 利用python对websocket进行并发压测
  5. 11_Swagger
  6. 关于HM NISEDIT在新版系统下编译并运行提示权限不足问题的解决方案
  7. JAVA员工名字 年龄 工资 工种
  8. Linux实战笔记_CentOS7_无法识别NTFS格式的U盘
  9. Python学习笔记----操作字符串
  10. sql面试50题------(21-30)