zoukankan      html  css  js  c++  java
  • 合并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
                
                
            
    

      

  • 相关阅读:
    [ARC074C] RGB Sequence
    [SHOI2014] 概率充电器
    CF368B Sereja and Suffixes
    CF980D Perfect Groups
    Rainbow Roads(gym101617G)(DFS序,差分)
    Educational Codeforces Round 104 (Rated for Div. 2)(A~E)
    Floor and Mod(CF1485C)(数论)
    Longest Simple Cycle(CF1476C)(线性dp)
    Factories(Gym102222G)(树形dp+背包)
    Codeforces Round #699 (Div. 2)(A,B,C,D)
  • 原文地址:https://www.cnblogs.com/importsober/p/13185923.html
Copyright © 2011-2022 走看看