题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类vector
* @return ListNode类
*/
ListNode* mergeKLists(vector<ListNode*>& lists) {
// write code here
int n=lists.size(),count=n;
auto *ans=new ListNode(-1001),*p=ans;
vector<int> v(n);
for(int i=0;i<n;++i){
if(lists[i]) v[i]=lists[i]->val;
else {
v[i]=1001;
count--;
}
}
while(count>0){
int index=0,min=v[0];
for(int i=0;i<n;++i){
if(v[i]<min){
index=i;
min=v[i];
}
}
ListNode *temp=lists[index];
lists[index]=lists[index]->next;
p->next=temp;
p=p->next;
if(lists[index]) v[index]=lists[index]->val;
else{
v[index]=1001;
count--;
}
}
return ans->next;
}
};

查看13道真题和解析