Leetcode.23. Merge k Sorted Lists

Posted hexsix

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode.23. Merge k Sorted Lists相关的知识,希望对你有一定的参考价值。

题意:合并几个有序链表,使结果也是有序的

题解1:循环遍历这几个链表头,将最小的加入结果链表中

技术分享图片
 1 class Solution {
 2 public:
 3     ListNode* mergeKLists(vector<ListNode*>& lists) {
 4         ListNode* res = NULL;
 5         ListNode* cur = res;
 6         while (true)
 7         {
 8             int target = 0;
 9             while (target < lists.size() && lists[target] == NULL)
10                 target++;
11             if (target >= lists.size())
12                 break;
13             for (auto i = 0; i < lists.size(); i++) {
14                 if (lists[i] == NULL) {
15                     continue;
16                 }
17 
18                 if (lists[target]->val > lists[i]->val)
19                     target = i;
20             }
21 
22             if (res == NULL) {
23                 res = new ListNode(lists[target]->val);
24                 cur = res;
25             }
26             else {
27                 cur->next = new ListNode(lists[target]->val);
28                 cur = cur->next;
29             }
30             lists[target] = lists[target]->next;
31         }
32         return res;
33     }
34 };
View Code

 

题解2:有一个取巧的办法,就是把所有元素取出来加入数组,对这个数组排序,再放回链表中

技术分享图片
 1 class Solution {
 2 public:
 3     ListNode* mergeKLists(vector<ListNode*>& lists) {
 4         vector<int> a;
 5         for (auto i = 0; i < lists.size(); i++)
 6         {
 7             ListNode* p = lists[i];
 8             while (p != NULL)
 9             {
10                 a.push_back(p->val);
11                 p = p->next;
12             }
13         }
14         sort(a.begin(), a.end());
15         ListNode* res = new ListNode(a[0]);
16         ListNode* cur = res;
17         for (auto i = 1; i < a.size(); i++) {
18             cur->next = new ListNode(a[i]);
19             cur = cur->next;
20         }
21         return res;
22     }
23 };
View Code

 

以上是关于Leetcode.23. Merge k Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 23. Merge k Sorted Lists

[LeetCode] 23. Merge k Sorted Lists 合并k个有序链表

[LeetCode]23. Merge k Sorted Lists

leetcode23. Merge k Sorted Lists

leetCode 23. Merge k Sorted Lists

leetcode 23. Merge k Sorted Lists