warriorprincess
06/01/2018, 7:27 PMfun mergeKLists(lists: Array<ListNode?>): ListNode? {
var holder: List<ListNode?> = arrayListOf()
while (true) {
val bulk = lists.withIndex().minBy { (_, value) -> value?.`val` ?: Int.MAX_VALUE }
val index = bulk?.component1(); val lowest = bulk?.component2() ?: break
holder += lowest
lists[index!!] = lists[index]?.next
}
for (index in 1 until holder.size) holder[index-1]?.next = holder[index]
return if (holder.isNotEmpty()) holder[0] else null
}Czar
06/01/2018, 7:32 PMilya.gorbunov
06/01/2018, 7:49 PMwhile loop to terminate?warriorprincess
06/01/2018, 7:57 PMwarriorprincess
06/01/2018, 7:57 PMlowest becomes null. it works correctly but perhaps not the best in terms of clarity?ilya.gorbunov
06/01/2018, 7:59 PMminBy returns null when there are no elements in lists, I don't see how lists array can become empty.ilya.gorbunov
06/01/2018, 8:06 PMval (index, lowest) = lists.withIndex().minBy { ... } ?: break
if (lowest == null) break
// here both index and lowest are not nullilya.gorbunov
06/01/2018, 8:10 PMholder += lowest that list is recreated, because it is declared as read-only and var.
If you declare it as val holder: MutableList<ListNode?> the values will be added to the existing mutable list.ilya.gorbunov
06/01/2018, 8:14 PMif (holder.isNotEmpty()) holder[0] else null can be replaced with holder.firstOrNull()warriorprincess
06/02/2018, 4:17 AMwarriorprincess
06/02/2018, 4:17 AMfun mergeKLists(lists: Array<ListNode?>): ListNode? {
val holder: MutableList<ListNode?> = arrayListOf()
while (true) {
val (index, lowest) = lists.withIndex().minBy { (_, value) -> value?.`val` ?: Int.MAX_VALUE } ?: break
if (lowest == null) break
holder += lowest
lists[index] = lists[index]?.next
}
for (index in 1 until holder.size) holder[index-1]?.next = holder[index]
return holder.firstOrNull()
}warriorprincess
06/02/2018, 4:18 AMilya.gorbunov
06/02/2018, 4:58 AMwithIndex in a tight loop, because it will create a lot of IndexedValue wrappers (number of lists x number of elements) I suppose.
Instead you can find the index of minimum element as following:
val indices = lists.indices
while(true) {
val indexOfMin = indices.minBy { lists[it]?.val ?: Int.MAX_VALUE } ?: break
val lowest = lists[indexOfMin] ?: breakwarriorprincess
06/02/2018, 7:48 AMindices.minBy { lists[it]?.val ?: Int.MAX_VALUE } ?: breakwarriorprincess
06/02/2018, 7:48 AMwarriorprincess
06/02/2018, 7:48 AMwarriorprincess
06/02/2018, 7:52 AM