zoukankan      html  css  js  c++  java
  • LeetCode #21 Merge Two Sorted Lists

    LeetCode #21 Merge Two Sorted Lists

    Question

    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.

    Solution

    Approach #1

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public var val: Int
     *     public var next: ListNode?
     *     public init(_ val: Int) {
     *         self.val = val
     *         self.next = nil
     *     }
     * }
     */
    class Solution {
        func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
            let dummy = ListNode(0)
            var current = dummy
            var p1 = l1
            var p2 = l2
            while let val1 = p1?.val, let val2 = p2?.val {
                if val1 < val2 {
                    current.next = p1
                    p1 = p1?.next
                } else {
                    current.next = p2
                    p2 = p2?.next
                }
                current = current.next!
            }
            current.next = p1 == nil ? p2 : p1
            return dummy.next
        }
    }
    

    Time complexity: O(m + n).

    Space complexity: O(1).

    Approach #2

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public var val: Int
     *     public var next: ListNode?
     *     public init(_ val: Int) {
     *         self.val = val
     *         self.next = nil
     *     }
     * }
     */
    class Solution {
        func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
            if l1 == nil { return l2 }
            if l2 == nil { return l1 }
            if l1!.val < l2!.val {
                l1!.next = mergeTwoLists(l1!.next, l2)
                return l1
            }
            l2!.next = mergeTwoLists(l1, l2!.next)
            return l2
        }
    }
    

    Time complexity: O(m + n).

    Space complexity: O(m + n).

    转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/6908177.html

  • 相关阅读:
    logistics regression
    dir 以及 attrib
    python 爬取有道翻译
    spss 逐步回归
    JQuery传值给.ashx乱码
    字符串转换成json的三种方式
    启动数据库SQL Server Service Broker
    ASP.NET两种缓存方式
    VS安装控件后报错
    sql server中有不是全数字的字符串
  • 原文地址:https://www.cnblogs.com/silence-cnblogs/p/6908177.html
Copyright © 2011-2022 走看看