Leetcode 23. Merge k Sorted Lists
2018-01-30 09:59
423 查看
原题:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
解决方法:
采用归并合并的方法,先两两合并,直到最终只剩下一个列表,就是我们所求结果。
代码:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
解决方法:
采用归并合并的方法,先两两合并,直到最终只剩下一个列表,就是我们所求结果。
代码:
ListNode* mergeTwoList(ListNode* l1, ListNode* l2){ ListNode dummy(INT_MIN); ListNode* cur = &dummy; while(l1 && l2){ if (l1->val < l2->val){ cur->next = l1; l1 = l1->next; }else{ cur->next = l2; l2 = l2->next; } cur = cur->next; } cur->next = l1 ? l1 : l2; return dummy.next; } ListNode* mergeKLists(vector<ListNode*>& lists) { if (lists.empty()) return NULL; while(lists.size() > 1){ for(int i = lists.size() -1; i > 0; i-=2){ lists.push_back(mergeTwoList(lists[i], lists[i-1])); lists.erase(lists.begin() + i); lists.erase(lists.begin() + i - 1); } } return lists.front(); }
相关文章推荐
- LeetCode之23---Merge k Sorted Lists
- leetcode23---Merge k Sorted Lists
- Leetcode 23. Merge k Sorted Lists (Hard) (cpp)
- LeetCode 23 Merge k Sorted Lists(合并K个已排序链表)
- [Leetcode] 23. Merge k Sorted Lists 解题报告
- LeetCode之23---Merge k Sorted Lists
- leetcode编程记录6 #23 Merge k Sorted Lists
- Leetcode 23. Merge k Sorted Lists
- LeetCode 23. Merge k Sorted Lists
- leetcode--23--Merge k Sorted Lists
- leetcode 23. Merge k Sorted Lists(Hard)
- leetcode problem :23. Merge k Sorted Lists
- leetcode 23:Merge k Sorted Lists(15-10-10)
- Leetcode 23 Merge k Sorted Lists
- [LeetCode]23. Merge k Sorted Lists
- LeetCode 23. Merge k Sorted Lists 【hard】
- Leetcode-23:Merge k Sorted Lists
- LeetCode - 21/23/88 - Merge Sorted Lists/Array
- Leetcode 23. Merge k Sorted Lists
- LeetCode | 23. Merge k Sorted Lists