题目:合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
格式:
输入 [[1,4,5],[1,3,4],[2,6]]
输出 [1,1,2,3,4,4,5,6]
思路:
合并几个有序的数组,不就是归并排序。显然用分治的思想。还有可以用堆。
题解:
方法一:分治(分治大法好)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists:return
num = len(lists)#遍历数组,看有多少有序链表
if num == 1:
return lists[0]
mid = int(num/2)
left = self.mergeKLists(lists[:mid])
right = self.mergeKLists(lists[mid:])
return self.merge2Lists(left,right)
def merge2Lists(self, left, right):#将两个有序链表合成一个有序链表
if not left:return right
if not right:return left
if left.val < right.val:
left.next = self.merge2Lists(left.next, right)
return left
else:
right.next = self.merge2Lists(left, right.next)
return right
方法二:堆(别人的代码,学习一下)
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0) {
return null;
}
ListNode dummyHead = new ListNode(0);
ListNode curr = dummyHead;
PriorityQueue<ListNode> pq = new PriorityQueue<>(new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val - o2.val;
}
});
for (ListNode list : lists) {
if (list == null) {
continue;
}
pq.add(list);
}
while (!pq.isEmpty()) {
ListNode nextNode = pq.poll();
curr.next = nextNode;
curr = curr.next;
if (nextNode.next != null) {
pq.add(nextNode.next);
}
}
return dummyHead.next;
}
}
196




被折叠的 条评论
为什么被折叠?



