10000 Revised Merging k Sorted Lists by lxieyang · Pull Request #81 · soulmachine/leetcode · GitHub
[go: up one dir, main page]

Skip to content

Revised Merging k Sorted Lists #81

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 15, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 27 additions & 23 deletions C++/chapSorting.tex
Original file line number Diff line number Diff line change
Expand Up @@ -98,34 +98,38 @@ \subsubsection{代码}
\begin{Code}
//LeetCode, Merge k Sorted Lists
// 时间复杂度O(n1+n2+...),空间复杂度O(1)
// TODO: 会超时
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &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<ListNode*>& lists) {
if(lists.size() == 0) return nullptr;

// multi pass
deque<ListNode *> 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}
Expand Down Expand Up @@ -276,7 +280,7 @@ \subsubsection{代码}
public:
int firstMissingPositive(vector<int>& nums) {
bucket_sort(nums);

for (int i = 0; i < nums.size(); ++i)
if (nums[i] != (i + 1))
return i + 1;
Expand Down Expand Up @@ -385,7 +389,7 @@ \subsubsection{代码3}
class Solution {
public:
void sortColors(vector<int>& nums) {
partition(partition(nums.begin(), nums.end(), bind1st(equal_to<int>(), 0)),
partition(partition(nums.begin(), nums.end(), bind1st(equal_to<int>(), 0)),
nums.end(), bind1st(equal_to<int>(), 1));
}
};
Expand Down
0