zoukankan      html  css  js  c++  java
  • 21. 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
    

    M1: iteration

    时间:O(M+N),空间:O(1)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode dummy = new ListNode(-1);
            ListNode cur = dummy;
            while(l1 != null && l2 != null) {
                if(l1.val < l2.val) {
                    cur.next = l1;
                    l1 = l1.next;
                }
                else {
                    cur.next = l2;
                    l2 = l2.next;
                }
                cur = cur.next;
            }
            cur.next = l1 == null ? l2 : l1;
            
            return dummy.next;
        }
    }

    M2: recursion

    时间:O(M+N),空间:O(M+N)

    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;
            }
        }
    }
  • 相关阅读:
    网址
    asp.net 各种路径查找
    jquery.nicescroll.js 滚动条插件 API
    课程表上一周下一周
    上一周下一周
    使用NPOI导入导出标准Excel
    FTP文件操作 上传文、 下载文件、删除文件 、创建目录
    asp.net断点续传
    11.06第九次作业
    11.20dezuoye
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10021841.html
Copyright © 2011-2022 走看看