LeetCode-21.Merge Two Sorted Lists | 合并两个有序链表

题目

LeetCode
LeetCode-cn

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

Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:

Input: l1 = [], l2 = []
Output: []

Example 3:

Input: l1 = [], l2 = [0]
Output: [0]
 

Constraints:
The number of nodes in both lists is in the range [0, 50].
-100 <= Node.val <= 100
Both l1 and l2 are sorted in non-decreasing order.

题解

这道题是经典的考察链表的题目。

解法一:递归

  • 终止条件:两条链表分别名为 l1l2,当 l1 为空或 l2 为空时结束
  • 返回值:每一层调用都返回排序好的链表头
  • 本级递归内容:如果 l1val 值更小,则将 l1.next 与排序好的链表头相接,l2 同理
  • O(m+n)O(m+n)mml1的长度,nnl2 的长度
//Go
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
    if l1 == nil {
        return l2;
    }else if l2 == nil {
        return l1;
    }else if (l1.Val < l2.Val) {
        l1.Next = mergeTwoLists(l1.Next, l2);
        return l1;
    }else {
        l2.Next = mergeTwoLists(l1, l2.Next);
        return l2;
    }
}

执行结果:

leetcode-cn:
执行用时:0 ms, 在所有 Go 提交中击败了100.00%的用户
内存消耗:2.6 MB, 在所有 Go 提交中击败了26.43%的用户

leetcode:
Runtime: 0 ms, faster than 100.00% of Go online submissions for Merge Two Sorted Lists.
Memory Usage: 2.6 MB, less than 51.09% of Go online submissions for Merge Two Sorted Lists.

可以看到,该解法执行用时为0ms,非常高效。

链接

力扣-画解算法:21. 合并两个有序链表

         
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明。
    
特此声明:所有评论和私信都会在第一时间回复。也欢迎园子里和园子外的大大们指正错误,共同进步。或者直接私信我 (^∀^)
    
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是作者坚持原创和持续写作的最大动力!

您的资助是我最大的动力!
金额随意,欢迎来赏!

如果,您认为阅读这篇博客让您有些收获,不妨点击一下右下角的推荐按钮。
如果,您希望更容易地发现我的新博客,不妨点击一下绿色通道的关注我

如果,想给予我更多的鼓励,求打

本博客的所有打赏均将用于博主女朋友的化妆品购买以及养肥计划O(∩_∩)O。我是【~不会飞的章鱼~】!

联系或打赏博主【~不会飞的章鱼~】!https://www.cnblogs.com/OctoptusLian/

原文地址:https://www.cnblogs.com/OctoptusLian/p/14391523.html