标签:des io for 代码 amp 时间 size ad
原题:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思路:两条两条地合并。时间复杂度为O(n),n为所有链表节点和。
代码:
/** * 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) { if(lists.empty()) return NULL; if(lists.size()==1) return lists[0]; ListNode *res; stack<ListNode*> now; int i = 0; ListNode *tmp1, *tmp2; now.push(lists[0]); now.push(lists[1]); i+=2; while(i<lists.size()){ tmp1 = now.top(); now.pop(); tmp2 = now.top(); now.pop(); res = mergeTwo(tmp1,tmp2); if(i>=lists.size()) break; now.push(res); now.push(lists[i]); i++; } return res; } ListNode *mergeTwo(ListNode* former, ListNode* later){ if(former==NULL && later!=NULL) return later; if(later==NULL && former!=NULL) return former; if(former==NULL && later==NULL) return NULL; ListNode *tmp = former, *tmp2 = later, *res, *head = NULL; if(tmp->val <= tmp2->val) { head = tmp; tmp = tmp->next; } else { head = tmp2; tmp2 = tmp2->next; } res = head; while(tmp && tmp2){ if(tmp->val>tmp2->val) { res->next = tmp2; tmp2 = tmp2->next; } else { res->next = tmp; tmp = tmp->next; } res =res->next; } if(tmp!=NULL) res->next = tmp; if(tmp2!=NULL) res->next = tmp2; return head; } };
【Leetcode长征系列】Merge k Sorted Lists,布布扣,bubuko.com
【Leetcode长征系列】Merge k Sorted Lists
标签:des io for 代码 amp 时间 size ad
原文地址:http://blog.csdn.net/u010239096/article/details/38560739