码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode合并两个有序链表

时间:2019-09-06 15:55:28      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:去掉   时间   图片   com   return   node   线性   solution   ext   

    技术图片

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

      if (l1 == null) {

          return l2;
      }    

      else if (l2 == null) {

          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;

      }

    }

}

复杂度分析

时间复杂度:O(n + m)O(n+m)。 因为每次调用递归都会去掉 l1 或者 l2 的头元素(直到至少有一个链表为空),函数 mergeTwoList 中只会遍历每个元素一次。所以,时间复杂度与合并后的链表长度为线性关系。

空间复杂度:O(n + m)O(n+m)。调用 mergeTwoLists 退出时 l1 和 l2 中每个元素都一定已经被遍历过了,所以 n + mn+m 个栈帧会消耗 O(n + m)O(n+m) 的空间。

Leetcode合并两个有序链表

标签:去掉   时间   图片   com   return   node   线性   solution   ext   

原文地址:https://www.cnblogs.com/TTTTTZ/p/11475148.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!