题目链接:https://leetcode-cn.com/problems/merge-k-sorted-lists/
1.一种暴力方法
首先,将所有节点添加到数组中O(n)。
然后,对数组进行升序排序O(nlogn)。
最后,将排好序的节点串起来O(n)。
总时间复杂度为 O(nlogn)
空间复杂度为 O(n)
Java代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0) return null;
// 将所有节点添加到数组中O(n)
List<ListNode> nodes = new ArrayList<>();
for (ListNode head : lists) {
while (head != null) {
nodes.add(head);
head = head.next;
}
}
// 对数组进行升序排序O(nlogn)
nodes.sort((ListNode node1, ListNode node2) -> {
return node1.val - node2.val;
});
// 将排好序的节点串起来O(n)
ListNode head = new ListNode(-1);
ListNode cur = head;
for (ListNode node : nodes) {
cur.next = node;
cur = cur.next;
}
return head.next;
}
}
C++代码如下:
// struct ListNode {
// int val;
// ListNode *next;
// ListNode() : val(0), next(nullptr) {}
// ListNode(int x) : val(x), next(nullptr) {}
// ListNode(int x, ListNode *next) : val(x), next(next) {}
// };
class CmpLess {
public:
bool operator() (const ListNode* node1, const ListNode* node2) {
return node1->val < node2->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.size() == 0) return nullptr;
// 将所有节点添加到数组中O(n)
vector<ListNode*> nodes;
for (auto head : lists) {
while (head != nullptr) {
nodes.push_back(head);
head = head->next;
}
}
// 对数组进行升序排序O(nlogn)
sort(nodes.begin(), nodes.end(), CmpLess());
// 将排好序的节点串起来O(n)
auto head = new ListNode(-1);
auto cur = head;
for (auto node : nodes) {
cur->next = node;
cur = cur->next;
}
// 这句本应该是多余的,但如果不写,LeetCode就会报错ERROR: AddressSanitizer: heap-use-after-free
cur->next = nullptr;
return head->next;
}
};