LeetCode23-合并K个升序链表
23. 合并K个升序链表:
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
1->4->5,
1->3->4,
2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6
示例 2:
输入:lists = []
输出:[]
示例 3:
输入:lists = [[]]
输出:[]
提示:
- k == lists.length
- 0 <= k <= 10^4
- 0 <= lists[i].length <= 500
- -10^4 <= lists[i][j] <= 10^4
- lists[i] 按 升序 排列
- lists[i].length 的总和不超过 10^4
解题思路1:
链表处理,多练习就行,每次找到最小的添加到新链表中
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* head=new ListNode(0);
ListNode* rethead=head;
int len=lists.size();
while(true) {
ListNode* minn=NULL;
int id=-1;
for(int i=0;i<len;++i) {
if(lists[i]==NULL)
continue;
if(minn==NULL) {
minn=lists[i];
id=i;
}
else if(minn->val > lists[i]->val) {
minn=lists[i];
id=i;
}
}
if(minn==NULL)
break;
head->next=minn;
lists[id]=lists[id]->next;
head=head->next;
}
return rethead->next;
}
};
解题思路2:
将所有节点放进优先队列中,保证每次取得最小值
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
struct myNode{
int val;
ListNode* node;
friend bool operator >(const myNode &a,const myNode &b){
return a.val>b.val;
}
};
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* head=new ListNode(0);
ListNode* retHead=head;
priority_queue<myNode,vector<myNode>,greater<myNode> >q;
int len=lists.size();
for(int i=0;i<len;++i)
if(lists[i]!=NULL)
q.push({lists[i]->val,lists[i]});
while(!q.empty()) {
myNode now=q.top();
q.pop();
head->next=now.node;
head=head->next;
now.node=now.node->next;
if(now.node)
q.push({now.node->val,now.node});
}
return retHead->next;
}
};