[leetcode]23. Merge k Sorted Lists归并k个有序链表

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

1 Input:
2 [
3   1->4->5,
4   1->3->4,
5   2->6
6 ]
7 Output: 1->1->2->3->4->4->5->6

题意:

归并k个有序链表。

思路:

用一个最小堆minHeap,将所有链表的头结点放入

新建一个linkedlist存储结果

minHeap里面每remove一个node(最小堆保证了该元素为当前堆中最小), 就加到新建linkedlist中,并将该node.next加入到堆里

代码:

 1 class Solution {
 2     public ListNode mergeKLists(ListNode[] lists) {
 3         // special case 
 4         if(lists.length==0) return null;
 5         // common case
 6         //1. priorityqueue ((o1,o2)-> o1.val, o2.val)
 7         PriorityQueue<ListNode> heap = new PriorityQueue<>((o1,o2)-> o1.val-o2.val);
 8       
 9         int size = lists.length;
10         for(int i = 0; i < size; i++){
11             if(lists[i]!=null){
12                 heap.add(lists[i]);  // add lists' head node  
13             }
14         }
15         //2. create a new linkedlist
16         ListNode fakeHead = new ListNode(-1);
17         ListNode current = fakeHead;
18         //3. add every node from priorityqueue's removing 
19         
20         while(heap.size()!=0){
21             ListNode node = heap.remove();
22             current.next = node;
23             current = current.next;
24             if(node.next!=null) heap.add(node.next);
25         }
26 
27       return fakeHead.next;  
28     }
29 }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9158321.html