[LeetCode] Merge k Sorted Lists

本文介绍了一种高效算法来合并多个已排序的链表。该算法通过不断合并未合并的链表直到只剩下一个链表的方式解决问题,并避免了顺序合并导致的时间效率低下问题。

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

Well, the idea of this problem is actually very sample --- keep merging the unmerged lists in lists until there is exactly one list remained. However, do not merge lists[0] with lists[1], lists[2], ..., lists[n - 1] sequentially since that will cause TLE. You may merge the first two lists and then push it back to lists and erase the first two to avoid repeated merging, or use some variables to control the merging process, as the following code.

 1 class Solution {
 2 public:
 3     ListNode* mergeKLists(vector<ListNode*>& lists) {
 4         if (lists.empty()) return NULL;
 5         int n = lists.size();
 6         while (n > 1) {
 7             for (int i = 0; i < n / 2; i++)
 8                 lists[i] = mergeLists(lists[i], lists[n - 1 - i]);
 9             n = (n + 1) / 2;
10         }
11         return lists[0];
12     }
13 private:
14     ListNode* mergeLists(ListNode* head1, ListNode* head2) {
15         ListNode* new_head = new ListNode(0);
16         ListNode* run = new_head;
17         ListNode* run1 = head1;
18         ListNode* run2 = head2;
19         while (run1 && run2) {
20             if (run1 -> val <= run2 -> val) {
21                 run -> next = run1;
22                 run1 = run1 -> next;
23             }
24             else {
25                 run -> next = run2;
26                 run2 = run2 -> next;
27             }
28             run = run -> next;
29         }
30         run -> next = run1 ? run1 : run2;
31         return new_head -> next;
32     }
33 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4623367.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值