# [LeetCode] 23. Merge k Sorted Lists 合并k个有序链表

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6

class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.empty()) return NULL;
int n = lists.size();
while (n > 1) {
int k = (n + 1) / 2;
for (int i = 0; i < n / 2; ++i) {
lists[i] = mergeTwoLists(lists[i], lists[i + k]);
}
n = k;
}
return lists[0];
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *dummy = new ListNode(-1), *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;
}
if (l1) cur->next = l1;
if (l2) cur->next = l2;
return dummy->next;
}
};

class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
auto cmp = [](ListNode*& a, ListNode*& b) {
return a->val > b->val;
};
priority_queue<ListNode*, vector<ListNode*>, decltype(cmp) > q(cmp);
for (auto node : lists) {
if (node) q.push(node);
}
ListNode *dummy = new ListNode(-1), *cur = dummy;
while (!q.empty()) {
auto t = q.top(); q.pop();
cur->next = t;
cur = cur->next;
if (cur->next) q.push(cur->next);
}
return dummy->next;
}
};

class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
return helper(lists, 0, (int)lists.size() - 1);
}
ListNode* helper(vector<ListNode*>& lists, int start, int end) {
if (start > end) return NULL;
if (start == end) return lists[start];
int mid = start + (end - start) / 2;
ListNode *left = helper(lists, start, mid);
ListNode *right = helper(lists, mid + 1, end);
return mergeTwoLists(left, right);
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (!l1) return l2;
if (!l2) return l1;
if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};

class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode *dummy = new ListNode(-1), *cur = dummy;
unordered_map<int, int> m;
int mx = INT_MIN, mn = INT_MAX;
for (auto node : lists) {
ListNode *t = node;
while (t) {
mx = max(mx, t->val);
mn = min(mn, t->val);
++m[t->val];
t = t->next;
}
}
for (int i = mn; i <= mx; ++i) {
if (!m.count(i)) continue;
for (int j = 0; j < m[i]; ++j) {
cur->next = new ListNode(i);
cur = cur->next;
}
}
return dummy->next;
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/23

Merge Two Sorted Lists

Ugly Number II

https://leetcode.com/problems/merge-k-sorted-lists/

https://leetcode.com/problems/merge-k-sorted-lists/discuss/10640/Simple-Java-Merge-Sort

https://leetcode.com/problems/merge-k-sorted-lists/discuss/10528/A-java-solution-based-on-Priority-Queue

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2015-06-29 08:59  Grandyang  阅读(...)  评论(...编辑  收藏