-
Notifications
You must be signed in to change notification settings - Fork 0
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
【Day 69 】2024-01-23 - 23. 合并 K 个排序链表 #73
Comments
// 21. 合并两个有序链表 var mergeKLists = function (lists) { |
[TOC] 思路
复杂度时间复杂度: 取决于小根堆插入排序的效率
空间复杂度:
Codeclass Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
if not lists: return None
que=[]
for i,node in enumerate(lists):
if node:heapq.heappush(que,(node.val,i,node))
dummy=ListNode()
cur=dummy
while que:
val,i,node=heapq.heappop(que)
cur.next=node
if node.next: heapq.heappush(que,(node.next.val,i,node.next))
cur=cur.next
return dummy.next |
|
思路分治 代码class Solution {
public ListNode mergeKLists(ListNode[] lists) {
return spiltAndMerge(lists, 0, lists.length - 1);
}
private ListNode spiltAndMerge(ListNode[] lists, int left, int right) {
if (left == right) {
return lists[left];
}
if (left > right) {
return null;
}
int mid = left + (right - left) / 2;
ListNode leftNode = spiltAndMerge(lists, left, mid);
ListNode rightNode = spiltAndMerge(lists, mid + 1, right);
return merge(leftNode, rightNode);
}
private ListNode merge(ListNode leftNode, ListNode rightNode){
if (leftNode == null) {
return rightNode;
}
if (rightNode == null) {
return leftNode;
}
if (leftNode.val < rightNode.val) {
leftNode.next = merge(leftNode.next, rightNode);
return leftNode;
} else {
rightNode.next = merge(leftNode, rightNode.next);
return rightNode;
}
}
} 复杂度
|
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
int k = lists.length;
ListNode dummyHead = new ListNode(0);
ListNode tail = dummyHead;
while (true) {
ListNode minNode = null;
int minPointer = -1;
for (int i = 0; i < k; i++) {
if (lists[i] == null) {
continue;
}
if (minNode == null || lists[i].val < minNode.val) {
minNode = lists[i];
minPointer = i;
}
}
if (minPointer == -1) {
break;
}
tail.next = minNode;
tail = tail.next;
lists[minPointer] = lists[minPointer].next;
}
return dummyHead.next;
}
} |
23. 合并 K 个排序链表
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/merge-k-sorted-lists/
前置知识
题目描述
The text was updated successfully, but these errors were encountered: