【发布时间】:2014-01-16 03:52:09
【问题描述】:
问题是“合并 k 个排序的链表并将其作为一个排序列表返回。”来自leetcode
1.
我的解决方案是使用一个向量来维护每个链表的当前位置,对向量进行排序得到最小值的节点,并将其插入到合并列表的末尾。代码如下:
bool cmp(ListNode *a, ListNode *b) {
return a->val < b->val;
}
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
ListNode *dummy = new ListNode(-1);
ListNode *curr = dummy;
//init
vector<ListNode*> currNodes;
for(int i = 0; i < lists.size(); ++i){
if(lists[i] != NULL){
currNodes.push_back(lists[i]);
}
}
while(!currNodes.empty()){
sort(currNodes.begin(), currNodes.end(), cmp);
curr->next = currNodes[0];
curr = curr->next;
if(currNodes[0]->next != NULL){
currNodes.push_back(currNodes[0]->next);
}
currNodes.erase(currNodes.begin());
}
return dummy->next;
}
};
由于 std::sort 的时间复杂度是 nlog(n) 并且我们有 (n1+n2...nk) 次迭代,因此我认为总时间复杂度是 O((n1+n2...+nk )klog(k))。但是在每次迭代中,向量currNodes 的大小可能会有所不同,所以我有点困惑。谁能证实这一点?
2。 我还在 leetcode 论坛上看到了另一个使用“合并排序”思想的解决方案。它每次合并两个链表。
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(lists.isEmpty()) return null;
if(lists.size() == 1) return lists.get(0);
int k = lists.size();
int log = (int)(Math.log(k)/Math.log(2));
log = log < Math.log(k)/Math.log(2)? log+1:log; // take ceiling
for(int i = 1; i <= log; i++){
for(int j = 0; j < lists.size(); j=j+(int)Math.pow(2,i)){
int offset = j+(int)Math.pow(2,i-1);
lists.set(j, mergeTwoLists(lists.get(j), (offset >= lists.size()? null : lists.get(offset))));
}
}
return lists.get(0);
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(l1 == null) return l2;
if(l2 == null) return l1;
ListNode head = l1.val > l2.val? l2:l1;
if(head.equals(l2)){
l2 = l1;
l1 = head;
}
while(l1.next != null && l2 != null){
if(l1.next.val > l2.val){
ListNode tmp = l1.next;
l1.next = l2;
l2 = l2.next;
l1 = l1.next;
l1.next = tmp;
}
else
l1 = l1.next;
}
if(l2 != null){
l1.next = l2;
}
return head;
}
}
我想知道这个解决方案的时间复杂度是多少?由于它每次都合并两个链表,因此存在 log(n) 次迭代。但是链表在每次迭代后都会变长(因为它是由两个链表合并而成的),如何计算每次迭代的时间复杂度,然后将它们相加?
提前谢谢你:)
【问题讨论】:
标签: c++ algorithm sorting merge mergesort