You are given an array of k
linked-lists lists
, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted list: 1->1->2->3->4->4->5->6
Example 2:
Input: lists = [] Output: []
Example 3:
Input: lists = [[]] Output: [] 就是用q啊
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param lists: a list of ListNode * @return: The head of one sorted list. */ //comparator private Comparator<ListNode> ListNodeComparator = new Comparator<ListNode>() { public int compare(ListNode left, ListNode right) { return left.val - right.val; } }; public ListNode mergeKLists(ListNode[] lists) { //new heap if (lists.length == 0 || lists == null) { return null; } Queue<ListNode> heap = new PriorityQueue<ListNode>(lists.length,ListNodeComparator); for (int i = 0; i < lists.length; i++) { if (lists[i] != null) { //先加每个的head,1 1 2,然后小的才有资格继续加 4 3 //加进来之后一起去和2比较,2更小,然后继续加 //把整个的list加进去 heap.add(lists[i]); } } //add to the lists ListNode dummy = new ListNode(0); ListNode tail = dummy; while(!heap.isEmpty()) { ListNode head = heap.poll(); System.out.println("head = " + head.val); tail.next = head; tail = head; if (head.next != null) { System.out.println("添加的head.next = " + head.next.val); System.out.println(" "); heap.add(head.next); } } return dummy.next; } }