LeetCode算法题–合并K个排序链表
- 题目来源:https://leetcode-cn.com/problems/merge-k-sorted-lists/
题目要求
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例1:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
题目思路:
将第 i 个链表和 第 n - i 个链表合并,依次两两合并。最后会得到一个链表。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
int length = lists.length;
if(length == 0){
return null;
}
while(length > 1){
for(int i = 0; i < length / 2; ++i){
lists[i] = mergeTwoList(lists[i], lists[length - i - 1]);
}
length = (length + 1) / 2; //剩余链表个数。
}
return lists[0];
}
public ListNode mergeTwoList(ListNode l1, ListNode l2){
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
ListNode head = new ListNode(0);
ListNode follow = head;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
follow.next = l1;
l1 = l1.next;
} else {
follow.next = l2;
l2 = l2.next;
}
follow = follow.next;
}
if(l1 == null){
follow.next = l2;
} else {
follow.next = l1;
}
return head.next;
}
}
执行结果:
时间复杂度:O(Nlog(k)) k为链表个数,N为链表数组中节点总个数。每一次归并所有节点都参与了一次,一共归并了logK 次 总的应该是O(Nlog(k))。