Skip to content

Instantly share code, notes, and snippets.

@hsaputra
Last active October 8, 2018 06:40
Show Gist options
  • Save hsaputra/b16d322aaa6237c409770dddfd4f6cb2 to your computer and use it in GitHub Desktop.
Save hsaputra/b16d322aaa6237c409770dddfd4f6cb2 to your computer and use it in GitHub Desktop.
/**
* 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;
}
}
@hsaputra
Copy link
Author

hsaputra commented Oct 8, 2018

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

Example:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment