Last active
December 3, 2018 21:41
-
-
Save scottashipp/c564c9b428d7e8e630c70ac3bfc4f999 to your computer and use it in GitHub Desktop.
Leetcode 23. Merge K sorted lists
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
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