[Link] https://leetcode.com/problems/merge-k-sorted-lists/
Slow runtime…Can improve this by unsing priorityque.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
ListNode curNode = new ListNode();
ListNode initNode = curNode;
int min;
while(true) {
ListNode minNode = new ListNode(Integer.MAX_VALUE);
int minIdx = -1;
for(int i = 0; i < lists.length; i++) {
ListNode node = lists[i];
if(node == null) continue;
if(minNode.val > node.val) {
minNode = node;
minIdx = i;
}
}
if(minIdx >= 0) {
curNode.next = minNode;
lists[minIdx] = lists[minIdx].next;
}
else break;
curNode = curNode.next;
}
return initNode.next;
}
}