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加入到堆里
代码:
public ListNode mergeKLists(ListNode[] lists) { if(lists == null || lists.length == 0) return null; PriorityQueue<ListNode> minHeap = new PriorityQueue<>((o1,o2)-> o1.val-o2.val);
for(int i = 0; i < lists.length; i++){ if(lists[i]!=null){ // 若<ListNode>类型,确保加入heap前确认该node不为null minHeap.add(lists[i]); } } ListNode dummy = new ListNode(-1); ListNode cur = dummy; while(minHeap.size() != 0){ ListNode node = minHeap.remove(); cur.next = node; cur = cur.next; if(node.next!=null) minHeap.add(node.next); } return dummy.next; }