[LeetCode题解]21. 合并两个有序链表 | 递归

解题思路

使用递归实现:

  1. 定义函数功能:合并两个有序链表,并返回链表的头
  2. 结束条件:两个链表其中一个为空,返回另一个链表
  3. 递推公式:
    • l1.val < l2.val:l1.next = MergeTwoLists(l1.next, l2)
    • l1.val >= l2.val:l2.next = MergeTwoLists(l1, l2.next)

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
        // 递归

        if(l1 == null) {
            return l2;
        }
        if(l2 == null) {
            return l1;
        }

        if(l1.val < l2.val) {
            l1.next = MergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = MergeTwoLists(l1, l2.next);
            return l2;
        }        
    }
}

复杂度分析

  • 时间复杂度:(O(n+m)),其中 (n)l1 的长度,(m)l2 的长度。一共 (n+m) 次递归调用,MergeTwoLists 的时间复杂度为 (O(1)),因此时间复杂度为 (O(n+m))
  • 空间复杂度:(O(n+m)),其中 (n)l1 的长度,(m)l2 的长度。一共 (n+m) 次递归调用,需要 (O(n+m)) 的额外空间。
原文地址:https://www.cnblogs.com/liang24/p/14015795.html