-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path23-MergeKSortedLists.kt
51 lines (49 loc) · 1.43 KB
/
23-MergeKSortedLists.kt
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
42
43
44
45
46
47
48
49
50
51
/**
*
* 23. Merge k Sorted Lists
* https://leetcode.com/problems/merge-k-sorted-lists/
*
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
* Solved using Count Sort approach
*/
import java.util.*
class Solution {
fun mergeKLists(lists: Array<ListNode?>): ListNode? {
val grouppedNodes: Map<Int, List<ListNode>> = groupNodes(lists)
return mergeLists(grouppedNodes)
}
fun groupNodes(lists: Array<ListNode?>): Map<Int, List<ListNode>> {
val grouppedNodes = TreeMap<Int, MutableList<ListNode>>()
lists.forEach { value ->
var head = value
while (head != null) {
grouppedNodes.computeIfAbsent(head.`val`) { mutableListOf() }
.add(head)
head = head.next
}
}
return grouppedNodes
}
fun mergeLists(grouppedNodes: Map<Int, List<ListNode>>): ListNode? {
var head: ListNode? = null
var pastNode: ListNode? = null
grouppedNodes.forEach { k, v ->
v.forEach { node ->
if (head == null) {
head = node
pastNode = node
}
pastNode?.next = node
pastNode = node
}
}
pastNode?.next = null
return head
}
}