合并K个排序链表
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
时间复杂度是O(N * log K) N是结点总数,K是链表总数
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
import java.util.Queue;
import java.util.PriorityQueue;
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length == 0) return null;
Queue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>(){
public int compare(ListNode l1, ListNode l2){
return l1.val - l2.val;
}
});
ListNode node = new ListNode(0);
ListNode p = node;
for(ListNode list : lists){
if(list != null)
queue.offer(list);
}
while(!queue.isEmpty()){
p.next = queue.poll();
p = p.next;
if(p.next != null) queue.offer(p.next);
}
return node.next;
}
}
合并K个排序数组
将 k 个有序数组合并为一个大的有序数组。
输入:
[
[1, 3, 5, 7],
[2, 4, 6],
[0, 8, 9, 10, 11]
]
输出: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
时间复杂度是O(N * log K) N是结点总数,K是链表总数
/**
* 合并K个有序数组,时间复杂度是O(n * log k) n : 是数组里的总数, K : 是多少个数组
* 时间复杂度为什么是O(n * log k),每个数组里的数加进堆里,堆的高度是logk, 所以每次加进堆的数的调整高度是logk,一共有n个数
*
*/
public class Solution {
class Element{
public int row;
public int col;
public int val;
public Element(int row, int col, int val){
this.row = row;
this.col = col;
this.val = val;
}
}
/**
* @param arrays: k sorted integer arrays
* @return: a sorted array
*/
public int[] mergekSortedArrays(int[][] arrays) {
// write your code here
if(arrays == null) return new int[]{};
int totalLen = 0;
Queue<Element> queue = new PriorityQueue<>(new Comparator<Element>(){
public int compare(Element e1, Element e2){
return e1.val - e2.val;
}
});
for(int i = 0; i < arrays.length; i++){
if(arrays[i].length > 0){
Element e = new Element(i, 0, arrays[i][0]);
queue.add(e);
}
totalLen += arrays[i].length;
}
int[] arr = new int[totalLen];
int index = 0;
while(!queue.isEmpty()){
Element el = queue.poll();
arr[index++] = el.val;
if(el.col + 1 < arrays[el.row].length){
el.col += 1;
el.val = arrays[el.row][el.col];
queue.offer(el);
}
}
return arr;
}
}