Saturday, August 15, 2015

Leetcode 21. Merge Two Sorted Lists

https://leetcode.com/problems/merge-two-sorted-lists/

Typical linked list problem. We can create a new list and add nodes to it.

Solution:
# T:O(m+n) S:O(m+n)
class Solution:
    # @param {ListNode} l1
    # @param {ListNode} l2
    # @return {ListNode}
    def mergeTwoLists(self, l1, l2):
        if l1 == None:
            return l2
        elif l2 == None:
            return l1
        dummy = ListNode(0)
        cur = dummy
        while l1 and l2:
            if l1.val <= l2.val:
                cur.next = l1
                l1 = l1.next
            else:
                cur.next = l2
                l2 = l2.next
            cur = cur.next
        else:
            cur.next = l1 or l2
        return dummy.next
Run Time: 64 ms

No comments:

Post a Comment