LeetCode 23. 合并K个排序链表 【时间击败98.35%】 【内存击败94.11%】

通过将逐一两两合并链表的方法优化为使用队列的假分治策略,实现链表合并,将运行时间从118ms大幅降低至4ms。介绍了关键代码变化,展示了如何利用队列提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原本是“逐一两两合并链表”,用时118ms,换成假分治后只用4ms,震惊!代码其实就是把遍历换成了队列……
关键代码变化:
“分治”:
1 static public ListNode mergeKLists(ListNode[] lists) {
2         if (lists == null || lists.length == 0) return null;
3         Queue<ListNode> q = new ArrayDeque<>();
4         for (ListNode n : lists) if (n != null) q.add(n);
5         while (q.size() > 1) {
6             q.add(merge2(q.poll(), q.poll()));
7         }
8         return q.poll();
9     }

逐一两两合并链表:

1     public ListNode mergeKLists(ListNode[] lists) {
2         if (lists.length==0)return null;
3         ListNode head = lists[0];
4         for (int i = 1; i < lists.length; i++) head = merge2(head, lists[i]);
5         return head;
6     }

有毒……

 1 import java.util.ArrayDeque;
 2 import java.util.Queue;
 3 
 4 public class Solution {
 5     static public ListNode mergeKLists(ListNode[] lists) {
 6         if (lists == null || lists.length == 0) return null;
 7         Queue<ListNode> q = new ArrayDeque<>();
 8         for (ListNode n : lists) if (n != null) q.add(n);
 9         while (q.size() > 1) {
10             q.add(merge2(q.poll(), q.poll()));
11         }
12         return q.poll();
13     }
14 
15     static ListNode merge2(ListNode l1, ListNode l2) {
16         if (l1 == null) return l2;
17         if (l2 == null) return l1;
18 
19         if (l1.val > l2.val) {
20             ListNode t = l1;
21             l1 = l2;
22             l2 = t;
23         }
24 
25         ListNode head = l1;
26         while (l1 != null && l2 != null) {
27             while (l1.next != null && l1.next.val < l2.val) l1 = l1.next;
28             if (l1.next == null) {
29                 l1.next = l2;
30                 return head;
31             }
32             ListNode next = l1.next;
33             l1.next = l2;
34             while (l2.next != null && l2.next.val < next.val) l2 = l2.next;
35             ListNode t = l2;
36             l2 = l2.next;
37             t.next = next;
38             l1 = next;
39         }
40         return head;
41     }
42 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值