题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param lists ListNode类一维数组 # @return ListNode类 # class Solution: def listUpdate(self,node:ListNode,lists: List[ListNode]): lists.remove(node) if(node.next!=None): lists.append(node.next) def mergeKLists(self , lists: List[ListNode]) -> ListNode: # write code here lists = [node for node in lists if node != None] k = len(lists) if(k == 0): return None if(k==1): return lists[0] lists =sorted(lists,key= lambda x: x.val) start = lists[0] res = start self.listUpdate(start,lists) cur = min(lists,key= lambda x: x.val) while(cur!=None): res.next = ListNode(cur.val) res = res.next self.listUpdate(cur,lists) if(len(lists) == 0): break cur = min(lists,key= lambda x: x.val) return start
钻牛角尖算法,直接把lists更新然后找最小的接起来,脑残算法,感谢python