Skip to content

Instantly share code, notes, and snippets.

@scottashipp
Last active December 3, 2018 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottashipp/c564c9b428d7e8e630c70ac3bfc4f999 to your computer and use it in GitHub Desktop.
Save scottashipp/c564c9b428d7e8e630c70ac3bfc4f999 to your computer and use it in GitHub Desktop.
Leetcode 23. Merge K sorted lists
import java.util.PriorityQueue;
class Solution {
class ListNodeWrapper implements Comparable<ListNodeWrapper> {
int listNumber;
int val;
ListNodeWrapper(int listNumber, ListNode listNode) {
this.listNumber = listNumber;
this.val = listNode.val;
}
@Override
public int compareTo(ListNodeWrapper listNodeWrapper) {
return this.val - listNodeWrapper.val;
}
}
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNodeWrapper> nextValues = initQueue(lists);
ListNode result = null;
ListNode ptr = null;
while(!nextValues.isEmpty()) {
ListNodeWrapper ln = nextValues.poll();
if(result == null) {
result = lists[ln.listNumber];
ptr = result;
} else {
ptr.next = lists[ln.listNumber];
ptr = ptr.next;
}
if(lists[ln.listNumber] != null) {
lists[ln.listNumber] = lists[ln.listNumber].next;
}
if(lists[ln.listNumber] != null) {
nextValues.add(new ListNodeWrapper(ln.listNumber, lists[ln.listNumber]));
}
}
return result;
}
private PriorityQueue<ListNodeWrapper> initQueue(ListNode[] lists) {
PriorityQueue<ListNodeWrapper> nextValues = new PriorityQueue<>();
for(int x = 0; x < lists.length; x++) {
if(lists[x] == null) {
continue;
}
ListNodeWrapper ln = new ListNodeWrapper(x, lists[x]);
nextValues.add(ln);
}
return nextValues;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment