首页 > 其他 > 详细

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

时间:2020-06-24 10:20:28      阅读:70      评论:0      收藏:0      [点我收藏+]
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
            
            
        

  

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!