Merge k Sorted Lists LeetCode solution in Java

1
class Solution {
2
public ListNode mergeKLists(ListNode[] lists) {
3
if (lists == null || lists.length < 1) return null;
4

5
// add the first chunk of linkedlist to res,
6
// so later we started from index 1
7
ListNode res = lists[0];
8

9
// traverse the lists and start merge by calling mergeTwo
10
for (int i = 1; i < lists.length; i++) {
11
res = mergeTwo(res, lists[i]);
12
}
13

14
return res;
15
}
16

17
// leetcode 21 technics
18
private ListNode mergeTwo(ListNode l1, ListNode l2) {
19
if (l1 == null) return l2;
20
if (l2 == null) return l1;
21

22
if (l1.val < l2.val) {
23
l1.next = mergeTwo(l1.next, l2);
24
return l1;
25
} else {
26
l2.next = mergeTwo(l2.next, l1);
27
return l2;
28
}
29
}
30
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0