题解 | #合并k个已排序的链表#

合并k个已排序的链表

https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

package main

import . "nc_tools"

/*
 * type ListNode struct{
 *   Val int
 *   Next *ListNode
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param lists ListNode类一维数组
 * @return ListNode类
 */
func mergeKLists(lists []*ListNode) *ListNode {
	// write code here
    if len(lists) == 0 {
        return nil
    } else if len(lists) == 1 {
        return lists[0]
    } else {
        return mergeTwoLists(mergeKLists(lists[:len(lists)/2]), mergeKLists(lists[len(lists)/2:]))
    }
}

func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
	l1 := make([]*ListNode, 0)
	l2 := make([]*ListNode, 0)
	node1, node2 := list1, list2
	for node1 != nil {
		l1 = append(l1, node1)
		node1 = node1.Next
	}
	for node2 != nil {
		l2 = append(l2, node2)
		node2 = node2.Next
	}
	i, j := len(l1)-1, len(l2)-1
	for i >= 0 && j >= 0 {
		if l1[i].Val > l2[j].Val {
			i--
		} else {
			next := l1[i].Next
			l1[i].Next = l2[j]
			l2[j].Next = next
			j--
		}
	}

	var head *ListNode
	if j >= 0 {
		if len(l1) > 0 {
			l2[j].Next = l1[0]
			head = l2[0]
		} else {
			head = list2
		}
	} else {
		if len(l1) > 0 {
			head = l1[0]
		} else {
			head = list1
		}
	}
	return head
}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
在秋招的河老师很爱吃:40岁失业 假如22岁开始工作 18年前 2007年那个时候如何 2015年开始互联网爆发 这个时候有了8年经验 然后黄金10年 你想想这些年挣了多少 这要是进的时候某个大厂 这辈子根本花不完了
你找实习最大的坎坷是什么
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务