• 合并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
                
                
            
    

      

  • 相关阅读:
    毕业面试试题汇总
    js获取系统日期
    非常酷的3D翻转相册展示特效
    CSS 替换元素和非替换元素 行内非替换元素
    怎样在linux下编写C程序并编译执行
    库和框架的区别
    转载:em(倍)与px的区别
    RPMForge介绍及安装
    linux下安装jdk和配置环境变量
    PCI PCI-X PCI-E介绍
  • 原文地址:https://www.cnblogs.com/importsober/p/13185923.html
Copyright © 2020-2023  润新知