Leetcode 23. Merge k Sorted Lists

Posted Hwangzhiyoung

tags:

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

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

题目意思:k个有序链表合并后仍为一个有序链表

解题思路:我先将链表存储在vector中,然后我用新的vector去存储链表中的每个节点,之后快速排序(stl std::sort),然后再对排序过后的节点组成链表,不是最优解,但是一个比较容易想的方法,时间复杂度是O(kn*logkn)

 1 #include <stdio.h>
 2 
 3 struct ListNode {
 4      int val;
 5     ListNode *next;
 6     ListNode(int x) : val(x), next(NULL) {}
 7 };
 8 
 9 #include <vector>
10 #include <algorithm>
11 
12 bool cmp(const ListNode *a, const ListNode *b){
13     return a->val < b->val;
14 }
15 
16 class Solution {
17 public:
18     ListNode* mergeKLists(std::vector<ListNode*>& lists) {
19         std::vector<ListNode *> node_vec;        
20         for (int i = 0; i < lists.size(); i++){
21             ListNode *head = lists[i];
22             while(head){
23                 node_vec.push_back(head);
24                 head = head->next;
25             }
26         }
27         if (node_vec.size() == 0){
28             return NULL;
29         }        
30         std::sort(node_vec.begin(), node_vec.end(), cmp);
31         for (int i = 1; i < node_vec.size(); i++){
32             node_vec[i-1]->next = node_vec[i];
33         }
34         node_vec[node_vec.size()-1]->next = NULL;
35         return node_vec[0];
36     }
37 };
38 
39 int main(){
40     ListNode a(1);
41     ListNode b(4);
42     ListNode c(6);
43     ListNode d(0);
44     ListNode e(5);
45     ListNode f(7);
46     ListNode g(2);
47     ListNode h(3);
48     a.next = &b;
49     b.next = &c;    
50     d.next = &e;
51     e.next = &f;    
52     g.next = &h;    
53     Solution solve;    
54     std::vector<ListNode *> lists;
55     lists.push_back(&a);
56     lists.push_back(&d);
57     lists.push_back(&g);    
58     ListNode *head = solve.mergeKLists(lists);
59     while(head){
60         printf("%d\\n", head->val);
61         head = head->next;
62     }
63     return 0;
64 }

 

通过~

 

以上是关于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