• 链表--合并两个有序链表(leetcode21


    迭代方法

    注意哑结点的使用,这会省去很多判断

    public ListNode mergeTwoLists(ListNode l1, ListNode l2){
            ListNode result = new ListNode(-1);
            ListNode tempResult = result;
            while(l1 != null&&l2 != null){
                if(l1.val <= l2.val){
                    tempResult.next = new ListNode(l1.val);
                    l1 = l1.next;
                    tempResult = tempResult.next;
                }else {
                    tempResult.next = new ListNode(l2.val);
                    l2 = l2.next;
                    tempResult = tempResult.next;
                }
            }
    
            tempResult.next = l1==null ? l2 : l1;
    
            return result.next;
        }
    

    代码倒数第二行也很简洁,一句话就能搞定的事情没必要写那么多判断

    时间复杂度:O(n+m)
    空间复杂度:O(1)


    递归解法

    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),其中 n 和 m 分别为两个链表的长度。递归调用 mergeTwoLists 函数时需要消耗栈空间,栈空间的大小取决于递归调用的深度。结束递归调用时 mergeTwoLists 函数最多调用 n+m 次,因此空间复杂度为 O(n+m)

  • 相关阅读:
    JQuery操作DOM
    JQuery事件和动画
    Jquery选择器
    初学JQuery
    JavaScript对象及面向对象
    JavaScript操作DOM
    JavaScript操作BOM
    JavaScript基础
    网络流之最大流Dinic算法模版
    杭电1532----Drainage Ditches『最大流』
  • 原文地址:https://www.cnblogs.com/swifthao/p/13019184.html
Copyright © 2020-2023  润新知