题目描述
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
解题代码
困难题第一次一遍过,但是用了递归还有for循环,就导致时间和空间复杂度都比较高。
func mergeKLists(lists []*ListNode) *ListNode { if len(lists) == 0 { return nil } if len(lists) == 1 { return lists[0] } lists = mergeKListsStep(lists) return mergeKLists(lists) } func mergeKListsStep(lists []*ListNode) []*ListNode { var list = &ListNode{Val: 0,Next: nil} p := list one := lists[0] two := lists[1] for one != nil && two != nil { if one.Val < two.Val { tem := one list.Next = tem list = list.Next one = one.Next } else { tem := two list.Next = tem list = list.Next two = two.Next } } if one == nil { list.Next = two } if two == nil { list.Next = one } lists = lists[2:] lists = append(lists, p.Next) return lists }
提交结果