问题描述
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思考:k路归并,用什么?排序
想法
- 1、利用最小堆。堆顶是最小元素,取出后调整堆。如果元素取出后链表为null,则将堆末尾的list放到堆顶。堆长度减一,并调整堆。
- 2、其实其他排序也可以。这里复习了最小堆
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
ListNode preHead = new ListNode(0);
preHead.next = null;
ListNode work = preHead;
int k = 0;
//初始化,去除为null的链表
for(int i = 0, j = 0; j < lists.length; j++)
if(lists[j] != null){
lists[i++] = lists[j];
k++;
}
creatHeap(lists,k);
while(k != 0){
work.next = lists[0];
ListNode temp = lists[0].next;
lists[0].next = null;
work = lists[0];
lists[0] = temp;
if(lists[0] == null){
k--;
lists[0] = lists[k];
}
minHeapify(lists,0,k);
}
return preHead.next;
}
//建堆
private void creatHeap(ListNode[] a, int len){
for(int i = len / 2 - 1; i >= 0; i--)
minHeapify(a, i, len);
}
//调整
private void minHeapify(ListNode[] a, int i, int len){
if(len < 2)
return;
int l = 2 * i + 1;
int r = 2 * i + 2;
int min = i;
while(true){
if(a[i] != null){
if(l < len && a[l].val < a[i].val )
min = l;
if(r < len && a[r].val < a[min].val)
min = r;
if(i != min)
swap(a,i,min); //此处可递归方法,这次写的是循环
else
break;
}
i = min;
l = 2 * min + 1;
r = 2 * min + 2;
}
}
//交换位置
private void swap(ListNode[] a, int i, int j){
ListNode temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}