LeetCode 23. 合并K个升序链表
题目描述
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
1->4->5,
1->3->4,
2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6
一、解题关键词
链表已经有顺序,两个链表合并的升级版
二、解题报告
1.思路分析
拆分list,进行两个list的合并
2.时间复杂度
3.代码示例
/**
* 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) {
//归并排序
int len = lists.length;
ListNode result = null;
for(int i = 0;i<len;i++){
result = mergeTwoList(result,lists[i]);
}
return result;
}
ListNode mergeTwoList(ListNode node1,ListNode node2){
if(node1 == null || node2 == null){
return node1 != null ? node1 : node2;
}
ListNode head = new ListNode(0);
ListNode tail = head,aptr = node1,bprt = node2;
while(aptr != null && bprt != null){
if(aptr.val < bprt.val){
tail.next = aptr;
aptr = aptr.next;
}else{
tail.next = bprt;
bprt = bprt.next;
}
tail = tail.next;
}
tail.next = (aptr != null ? aptr:bprt);
return head.next;
}
}
2.知识点
归并排序
总结
归并吧 链表!!!