Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public int findmin(ArrayList<ListNode> lists){
int min = 56789;
int index = -1;
for(int i = 0; i < lists.size(); i++){
//System.out.println("size" + lists.size());
if(lists.get(i) != null){
if(lists.get(i).val < min){
index = i;
min = lists.get(i).val;
}
}
}
if(index == -1)
return 56789;
else{
lists.set(index, lists.get(index).next);
//System.out.println("i" + index);
//System.out.println("min" + min);
return min;
}
}
public ListNode mergeKLists(ArrayList<ListNode> lists) {
ListNode root = new ListNode(0);
if(lists == null)
return null;
ListNode current = root;
while(true){
int result = findmin(lists);
if(result != 56789){
ListNode newnode = new ListNode(result);
current.next = newnode;
current = newnode;
newnode.next = null;
}
else if(result == 56789)
break;
}
return root.next;
}
}