File tree Expand file tree Collapse file tree 2 files changed +45
-1
lines changed
solution/023.Merge k Sorted Lists Expand file tree Collapse file tree 2 files changed +45
-1
lines changed Original file line number Diff line number Diff line change 17
17
### 解法
18
18
从链表数组索引 0 开始,[ 合并前后相邻两个有序链表] ( https://github.com/yanglbme/leetcode/tree/master/solution/021.Merge%20Two%20Sorted%20Lists ) ,放在后一个链表位置上,依次循环下去...最后 lists[ len - 1] 即为合并后的链表。注意处理链表数组元素小于 2 的情况。
19
19
20
+ --------------------------------
21
+ 思路1: 170ms
22
+ 用第一个链依次和后面的所有链进行双链合并,利用021的双顺序链合并,秒杀!但是效率极低
23
+ 时间复杂度是O(x(a+b) + (x-1)(a+b+c) + ... + 1 * (a+b+...+z);
24
+ 时间复杂度是极大的
25
+
26
+
27
+ 思路2: 20ms
28
+ 1.因为链表有序,所以用每个链表的首元素构建初试堆(小顶堆) -- 的队列
29
+ 2.首元素出队,该元素出队
30
+ 时间复杂度是O(n)
31
+
20
32
``` java
21
33
/**
22
34
* Definition for singly-linked list.
@@ -66,4 +78,35 @@ class Solution {
66
78
return l2;
67
79
}
68
80
}
69
- ```
81
+ ```
82
+
83
+ #### CPP
84
+
85
+ ``` C++
86
+ class Solution {
87
+ public:
88
+ ListNode* mergeKLists(vector<ListNode* >& lists) {
89
+ int len = lists.size();
90
+ if(len == 0)return NULL;
91
+
92
+ priority_queue<ListNode*,vector<ListNode*>,compare> Q;//调用小顶堆的方法构造队列!!!
93
+
94
+ for(int i = 0;i < len;i++)
95
+ {
96
+ if(lists[i])Q.push(lists[i]);
97
+ }
98
+
99
+ ListNode *head = new ListNode(0);
100
+ ListNode *tail = head;
101
+ while(!Q.empty() && Q.top() != NULL)
102
+ {
103
+ ListNode *tmp = Q.top();
104
+ Q.pop();
105
+ tail->next = tmp;
106
+ tail = tail->next;
107
+ Q.push(tmp->next);
108
+ }
109
+ return head->next;
110
+ }
111
+ };
112
+ ```
Original file line number Diff line number Diff line change @@ -13,6 +13,7 @@ class compare
13
13
}
14
14
};
15
15
16
+
16
17
class Solution {
17
18
public:
18
19
ListNode* mergeKLists (vector<ListNode*>& lists) {
You can’t perform that action at this time.
0 commit comments