Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Subscribe to see which companies asked this question
这道题试了多种方法,有堆排序和分zhi链表排序
class Solution { public: //这个会超时是因为排序到后面,其中一个链表会越来越长,导致合并的时间越来越长 ListNode *_mergeKLists(vector<ListNode *> &lists) { if (lists.empty()) return 0; if (lists.size() == 1) return lists.back(); vector<ListNode *> l; while (!lists.empty()) { if (lists.size() == 1) { l.push_back(lists.back()); lists.pop_back(); } else { ListNode *p = lists.back(); lists.pop_back(); ListNode *q = lists.back(); lists.pop_back(); l.push_back(mergeTwoLists(p, q)); } } return mergeKLists(l); } ListNode* mergeKLists(vector<ListNode*>& lists) { if (lists.empty()) { return NULL; } while (!lists.empty()) { if (1 == lists.size()) { return lists[0]; } ListNode *p1 = lists.back(); lists.pop_back(); ListNode *p2 = lists.back(); lists.pop_back(); lists.push_back(mergeTwoLists(p1, p2)); } } ListNode* mergeTwoLists(struct ListNode *l1, struct ListNode *l2){ if (l1 == NULL && l2 == NULL) { return NULL; } else if (l1 == NULL) { return l2; } else if (l2 == NULL) { return l1; } ListNode* phead; ListNode* node; ListNode* p1 = l1; ListNode* p2 = l2; if (p1->val <= p2->val) { phead = p1; p1 = p1->next; } else { phead = p2; p2 = p2->next; } node = phead; while (p1 != NULL && p2 != NULL) { if (p1->val <= p2->val) { node->next = p1; p1 = p1->next; } else { node->next = p2; p2 = p2->next; } node = node->next; } node->next = p1 ? p1 : p2; return phead; } };
posted on 2016-01-10 22:34 walkwalkwalk 阅读(181) 评论(0) 编辑 收藏 举报