zoukankan      html  css  js  c++  java
  • 【LeetCode每天一题】Merge Two Sorted Lists(合并两个排序链表)

    Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

    Example:        Input: 1->2->4, 1->3->4              Output: 1->1->2->3->4->4

    解决思路:最简单的办法是,直接将所有元素图取出来放入内存中,然后进行排序,将排序好的结果重新构造链表然后返回。但是这样做时间复杂度较高,O((m+n)log(m+n))(m, n分别为l1 和l2 的长度), 空间复杂度为O(m+n)。

          另一种办法是,依此进行比较大小,然后将小的节点插入申请链表节点尾部,循环遍历,直到其中一个链表便遍历完毕。时间复杂度为O(m+n), 空间复杂度为O(m+n)。

        步骤图如下:

                

     1 class Solution(object):
     2     def mergeTwoLists(self, l1, l2):
     3         """
     4         :type l1: ListNode
     5         :type l2: ListNode
     6         :rtype: ListNode
     7         """
     8         if not l1 or not l2:           # 其中一个空节点,直接返回非空的节点
     9             return l1 if l1 else l2
    10         res_node = p =  ListNode(0)    # 哨兵节点
    11         while l1 and l2:
    12             if l1.val < l2.val:     
    13                 p.next = l1            
    14                 l1 = l1.next
    15             else:
    16                 p.next = l2
    17                 l2 = l2.next
    18             p = p.next
    19         p.next = l1 or l2              # 将非空的节点加到尾部
    20         return res_node.next            # 返回排序后的节点
  • 相关阅读:
    Python_Day3
    Python_Day2
    动漫推荐3.0 杂谈
    动漫推荐2.0 杂谈
    动漫推荐1.0 剧情向
    西湖十大特产
    一到春天 杭州西湖就美成了一幅画
    机械键盘十大品牌排行榜
    键盘的日常维护及清理
    无线键盘
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10593452.html
Copyright © 2011-2022 走看看