归并思想,两两合并链表
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def merge(self, head1, head2):
pre = curr = ListNode(100)
while head1 and head2:
if head1.val <= head2.val:
curr.next = head1
curr = curr.next
head1 = head1.next
else:
curr.next = head2
curr = curr.next
head2 = head2.next
curr.next = head1 if head1 else head2
return pre.next
def mergeKLists(self, lists: List[ListNode]):
n = len(lists)
if n == 0:
return None
if n == 1:
return lists[0]
mid = n // 2
a = self.mergeKLists(lists[:mid])
b = self.mergeKLists(lists[mid:])
return self.merge(a, b)
堆排序思想
python
# @return ListNode类
#
import heapq
class Solution:
def mergeKLists(self , lists):
# write code here
n = len(lists)
pre = curr = ListNode(100)
heap = []
for index, node in enumerate(lists):
if node:
val = node.val
tup = (val, index, node)
heapq.heappush(heap, tup)
while heap:
val, index, node = heapq.heappop(heap)
curr.next = node
curr = curr.next
node = node.next
if node:
val = node.val
tup = (val, index, node)
heapq.heappush(heap, tup)
return pre.next
c++
/**
* Definition for singly-linked list.
* 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 Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
// 利用最小堆的性质 维护当前的最小节点值
ListNode* dummy = new ListNode(-1);
ListNode* pre = dummy;
function<bool(ListNode*, ListNode*)> cmp = [](ListNode* a, ListNode* b) { return a->val > b->val;};
priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> pq(cmp);
for (auto& head : lists) {
if (head) pq.push(head);
}
while (!pq.empty()) {
ListNode* curr = pq.top();
pre->next = curr;
pre = pre->next;
pq.pop();
if (curr->next != nullptr) pq.push(curr->next);
}
return dummy->next;
}
};