标签:效率 iterator etc style nod col 描述 .com ret
1、题目描述
2、问题分析
使用合并两个链表的方法,逐次合并,效率较低。可以考虑同时合并K个链表。
3、代码
1 ListNode* mergeKLists(vector<ListNode*>& lists) { 2 3 ListNode *res = NULL; 4 for (vector<ListNode*>::iterator it = lists.begin(); it != lists.end(); it++) { 5 res = mergeTwoLists(res, *it); 6 } 7 8 return res; 9 } 10 11 ListNode *mergeTwoLists(ListNode *list1, ListNode *list2) 12 { 13 if (list1 == NULL) 14 return list2; 15 if (list2 == NULL) 16 return list1; 17 18 ListNode *p1 = list1; 19 ListNode *p2 = list2; 20 ListNode *dummy = new ListNode(0); 21 ListNode *p = dummy; 22 while (p1 != NULL && p2 != NULL) { 23 if (p1->val <= p2->val) { 24 p->next = p1; 25 p1 = p1->next; 26 } else { 27 p->next = p2; 28 p2 = p2->next; 29 } 30 p = p->next; 31 } 32 33 while (p1 != NULL) { 34 p->next = p1; 35 p = p->next; 36 p1 = p1->next; 37 } 38 39 while (p2 != NULL) { 40 p->next = p2; 41 p = p->next; 42 p2 = p2->next; 43 } 44 return dummy->next; 45 }
LeetCode题解之 Merge k Sorted Lists
标签:效率 iterator etc style nod col 描述 .com ret
原文地址:https://www.cnblogs.com/wangxiaoyong/p/10422341.html