合併K個排序鏈表

合併 k 個排序鏈表,返回合併後的排序鏈表。請分析和描述算法的複雜度。node

示例:算法

輸入:
[
  1->4->5,
  1->3->4,
  2->6
]
輸出: 1->1->2->3->4->4->5->6
複製代碼
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if( lists.length == 0 ){
            return null;
        }
         PriorityQueue< ListNode > min = new PriorityQueue<>(lists.length ,new Comparator<ListNode>(){
           @Override
           public int compare( ListNode o1 , ListNode o2 ){
               return o1.val - o2.val;
           }
       });
       for( ListNode list : lists ){
           if( list != null )
           min.offer( list );
       }
       ListNode dummy =  new ListNode(-1);
       ListNode cur = dummy; 
       while( min.size() != 0 ){
           ListNode node = min.poll();
           cur.next = node;
           cur = node;
           if( node.next != null )
           min.offer( node.next );
       } 
       return dummy.next; 
    }
}
複製代碼

解題思路: 用大小爲數組長度的最小堆來處理, 先把全部鏈表放進堆中 ,而後每次彈出堆頂元素 , 若是彈出元素還有下一個結點 , 則繼續放進堆中。 時間複雜度: 假設鏈表平均長度爲n , 數組個數爲k , 則須要取n*k個元素, 更新堆須要logk, 則總時間爲nklogk.數組

相關文章
相關標籤/搜索