先贴TLE的代码。每次遍历取出最小值
/**
* @author johnsondu
* @problem Merge k Sorted Lists
* @url https://leetcode.com/problems/merge-k-sorted-lists/
* @timeComlexity O(nm) where n is maximum list length, and m is number of lists.
* @spaceComplexity O(n)
* @strategy List Insert
* @status Time Limited Error
* @time 22:41, Oct 9 2015
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode *head = new ListNode(0);
ListNode *root = head;
while(1) {
bool flag = false;
for(int i = 0; i < lists.size(); i ++)
if(lists[i] != NULL) flag = true;
if(!flag) break;
flag = false;
int cur;
int index = 0;
for(int i = 0; i < lists.size(); i ++)
{
if(lists[i]) {
if(!flag) {
flag = true;
cur = lists[i]->val;
index = i;
}
else {
if(cur > lists[i]->val) {
cur = lists[i]->val;
index = i;
}
}
}
}
ListNode *tmp = new ListNode(cur);
head->next = tmp;
head = head->next;
lists[index] = lists[index]->next;
}
return root->next;
}
};
解决合并K个已排序链表的问题
本文探讨了如何高效地将K个已排序的链表合并为一个已排序的链表,提供了时间复杂度为O(nm),空间复杂度为O(n)的解决方案,其中n是列表中最长列表的长度,m是列表的数量。
1456

被折叠的 条评论
为什么被折叠?



