-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path23. Merge k Sorted Lists
41 lines (40 loc) · 1.19 KB
/
23. Merge k Sorted Lists
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
38
39
40
41
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length == 0){
return null;
}
return helper(lists,0,lists.length-1);
}
public ListNode helper(ListNode[] lists , int start ,int end){
if(start > end ){
return null;
}
if(start == end){
return lists[start];//here start can be any thing start or end;
}
int mid = start + (end - start)/2;
ListNode left = helper(lists, start , mid);
ListNode right = helper(lists, mid + 1, end);
return merge(left , right);
}
public ListNode merge(ListNode l1 , ListNode l2){
ListNode temp = new ListNode(-1);
ListNode sol = temp;
while (l1 != null && l2 != null){
if(l1.val > l2.val){
temp.next = l2;
l2 = l2.next;
temp = temp.next;
}
else {
temp.next = l1;
l1 = l1.next;
temp = temp.next;
}
}
if(l1 != null || l2 != null){
temp.next = l1 != null ? l1 : l2;
}
return sol.next;
}
}