题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/** * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ object Solution { private lateinit var retCurrent: ListNode /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param lists ListNode类一维数组 * @return ListNode类 */ fun mergeKLists(lists: Array<ListNode?>): ListNode? { // write code here val currentNodeList = lists.map { it }.toMutableList() val vRetHead = ListNode(-1) retCurrent = vRetHead while (!isAllCurrentNull(currentNodeList)) { var min = Int.MAX_VALUE var minNodeIndex: Int = -1 currentNodeList.forEachIndexed { index, it -> if (it == null) { return@forEachIndexed } if (it.`val` < min) { minNodeIndex = index min = it.`val` } } if (minNodeIndex != -1) { currentNodeList[minNodeIndex] = toNext(currentNodeList[minNodeIndex]!!) } } return vRetHead.next } private fun isAllCurrentNull(currentList: List<ListNode?>): Boolean { return currentList.filterNotNull().isEmpty() } private fun toNext(current: ListNode): ListNode? { val next = current.next retCurrent.next = current retCurrent = current return next } }