0023_ Merging K sorted lists
Title Description
Merges the K sorted list and returns the sorted list after the merge. Please analyze and describe the complexity of the algorithm.
Example:
输入:[ 1->4->5, 1->3->4, 2->6]输出: 1->1->2->3->4->4->5->6
Algorithm
Type listnode struct {Val int Next *listnode}func mergeklists (lists []*listnode) *listnode {n: = Len (lists) Switch N {case 0:return nil 1:return lists[0] 2://merge sort for two linked lists return Merge (Lists[0], lists[1]) Default:key: = N/2//array split, the length of the next recursive lists = 2//Optimization idea: mergeklists (lists [: Key]), using Goroutine+channel for concurrent merging (features of merge sort) return mergeklists ([]*listnode{mergeklists (Lists[:key]), mergeklists ( Lists[key:]})}}//merge two ordered linked list of the merge sort func merge (left *listnode, right *listnode) *listnode {//head: New linked list head pointer, hold Invariant//tail: New linked list's tail pointer var head, tail *listnode if left = = nil {return Right} if right = = Nil { Return left} if left. Val < Right. Val {head, tail, left = left, left, left. Next} else {head, tail, right = right, right, right. Next}//loop until a linked list has traversed for Left! = Nil && Right! = Nil {//Find the next node, add to the tail if lef of the new linked listT.val < Right. Val {tail. Next, left = left and left. Next} else {tail. Next, right = right and right. Next}//update tail tail = tail. Next}//The remaining node bytes are stitched to the new linked list tail if left! = nil {tail. Next = left} if right! = nil {tail. Next = right} return head}
Personal ideas
1. 对已经有序的多个链表进行合并,可以借鉴归并排序,分治法的思想,层层递归2. 两个链表可以进行遍历比较节点大小,合并为一个新的链表
Summarize
- Divide and conquer the characteristics of the law: each layer of the recursive can be carried out at the same time, the optimization of ideas can be used Goroutine+channel, the author is not optimized, not the focus of this article
Recursion pros and cons
Advantages:
1. 代码简洁
Disadvantages:
1. 空间消耗大,每一次函数调用都需要在内存栈中分配空间保存参数,返回地址以及临时变量2. 栈里面压入和弹出都需要时间3. 递归有栈溢出的问题
Cycle
Advantages
1. 和递归相比,空间消耗小
Disadvantages
1. 代码可读性不如递归
GitHub
- Project Source is here
- The author will always maintain the project, solve the algorithm problem in Leetcode, and write down his own ideas and opinions, and devote to the algorithm that everyone can understand.
Personal public number
- Favorite friends can pay attention to, thank you for your support
- Record the learning and life of the farmers in the code