From a4291d8a8c057e9649e2b0ee15aeab4ae9a3b032 Mon Sep 17 00:00:00 2001 From: Xieyang Liu Date: Sat, 13 Feb 2016 15:51:34 -0500 Subject: [PATCH 1/2] revised: merge k sorted lists --- C++/chapSorting.tex | 49 +++++++++++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 22 deletions(-) diff --git a/C++/chapSorting.tex b/C++/chapSorting.tex index c20162d4..f686e0a3 100644 --- a/C++/chapSorting.tex +++ b/C++/chapSorting.tex @@ -101,31 +101,36 @@ \subsubsection{代码} // TODO: 会超时 class Solution { public: - ListNode *mergeKLists(vector &lists) { - if (lists.size() == 0) return nullptr; - ListNode *p = lists[0]; - for (int i = 1; i < lists.size(); i++) { - p = mergeTwoLists(p, lists[i]); + ListNode * mergeTwo(ListNode * l1, ListNode * l2){ + if(!l1) return l2; + if(!l2) return l1; + ListNode dummy(-1); + ListNode * p = &dummy; + for(; l1 && l2; p = p->next){ + if(l1->val > l2->val){ + p->next = l2; l2 = l2->next; + } + else{ + p->next = l1; l1 = l1->next; + } } - return p; + p->next = l1 ? l1 : l2; + return dummy.next; } - // Merge Two Sorted Lists - ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { - ListNode head(-1); - for (ListNode* p = &head; l1 != nullptr || l2 != nullptr; p = p->next) { - int val1 = l1 == nullptr ? INT_MAX : l1->val; - int val2 = l2 == nullptr ? INT_MAX : l2->val; - if (val1 <= val2) { - p->next = l1; - l1 = l1->next; - } else { - p->next = l2; - l2 = l2->next; - } + ListNode* mergeKLists(vector& lists) { + if(lists.size() == 0) return nullptr; + + // multi pass + deque dq(lists.begin(), lists.end()); + while(dq.size() > 1){ + ListNode * first = dq.front(); dq.pop_front(); + ListNode * second = dq.front(); dq.pop_front(); + dq.push_back(mergeTwo(first,second)); } - return head.next; + + return dq.front(); } }; \end{Code} @@ -276,7 +281,7 @@ \subsubsection{代码} public: int firstMissingPositive(vector& nums) { bucket_sort(nums); - + for (int i = 0; i < nums.size(); ++i) if (nums[i] != (i + 1)) return i + 1; @@ -385,7 +390,7 @@ \subsubsection{代码3} class Solution { public: void sortColors(vector& nums) { - partition(partition(nums.begin(), nums.end(), bind1st(equal_to(), 0)), + partition(partition(nums.begin(), nums.end(), bind1st(equal_to(), 0)), nums.end(), bind1st(equal_to(), 1)); } }; From d4ee008ca19c3c58af54a92214f5d09a35dd9057 Mon Sep 17 00:00:00 2001 From: Xieyang Liu Date: Sat, 13 Feb 2016 15:52:48 -0500 Subject: [PATCH 2/2] revised merge k sorted lists --- C++/chapSorting.tex | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/chapSorting.tex b/C++/chapSorting.tex index f686e0a3..f92c115a 100644 --- a/C++/chapSorting.tex +++ b/C++/chapSorting.tex @@ -98,7 +98,6 @@ \subsubsection{代码} \begin{Code} //LeetCode, Merge k Sorted Lists // 时间复杂度O(n1+n2+...),空间复杂度O(1) -// TODO: 会超时 class Solution { public: