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;
            }
        }
    }
  • 相关阅读:
    Java 调用存储过程、函数
    Java BaseDao
    写好Java代码的30条经验总结
    15款Java程序员必备的开发工具
    Oracle基础 表分区
    Oracle基础 索引
    Oracle基础 触发器
    Oracle基础 程序包
    Oracle基础 自定义函数
    Oracle基础 存储过程和事务
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10021841.html
Copyright © 2011-2022 走看看