Last active
October 8, 2018 06:40
-
-
Save hsaputra/b16d322aaa6237c409770dddfd4f6cb2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 == null) { | |
throw new IllegalArgumentException(); | |
} | |
final int k = lists.length; | |
if (k == 1) { | |
return lists[0]; | |
} | |
// Let's do k-way merge | |
PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>(new Comparator<ListNode>() { | |
@Override | |
public int compare(ListNode o1, ListNode o2) { | |
return o1.val - o2.val; | |
} | |
}); | |
// Add first k nodes from the list. | |
for (ListNode node : lists) { | |
if (node != null) { | |
pq.offer(node); | |
} | |
} | |
// Now iterate through the PQ, once popped, add next one from the list. | |
ListNode tmpResult = new ListNode(-1); | |
ListNode cur = tmpResult; | |
while (pq.peek() != null) { | |
ListNode nodeCur = pq.poll(); | |
cur.next = new ListNode(nodeCur.val); | |
cur = cur.next; | |
// check if more from the list | |
ListNode nextCur = nodeCur.next; | |
if (nextCur != null) { | |
pq.offer(nextCur); | |
} | |
} | |
return tmpResult.next; | |
} | |
} |
Author
hsaputra
commented
Oct 8, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment