题解 | #合并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
    }

}



全部评论

相关推荐

面试摇了我吧:啊哈哈面试提前五个小时发,点击不能参加就是放弃
点赞 评论 收藏
分享
喜欢走神的孤勇者练习时长两年半:爱华,信华,等华,黑华
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务