合併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;
}
}