合并k个有序链表, LeetCode题解(二)

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

合并链表很简单,而且还是有序的,k个指针前进就行。写代码的时候只要随时记得保持良好习惯,尽量用少量的判断来包括多种条件进去,这样写出来的代码就不会和严蔚敏的数据结构书上一样丑了。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        k_cursors = [i for i in lists if i ]
        result = ListNode()
        cursor = result

        while len(k_cursors) > 0:
            smallest = self.find_smallest_in_k_cursors(k_cursors)
            new_node = ListNode(smallest)
            cursor.next = new_node
            cursor = cursor.next
        result = result.next
            
        return result
    def find_smallest_in_k_cursors(self, k_cursors):
        smallest = float("inf")
        remeber_cursor = {}
        for i, k_cursor in enumerate(k_cursors):
            if k_cursors[i].val < smallest:
                smallest = k_cursors[i].val
                remeber_cursor[smallest] =  i
        if not k_cursors[remeber_cursor[smallest]].next:
            k_cursors.pop(remeber_cursor[smallest])
        else:
            k_cursors[remeber_cursor[smallest]] = k_cursors[remeber_cursor[smallest]].next
        return smallest
            
            
        

  

原文地址:https://www.cnblogs.com/importsober/p/13185923.html