Page tree
Skip to end of metadata
Go to start of metadata

Memory Usage: less than 99.99%

Merge Two Sorted Lists
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
    cur1 = l1
    cur2 = l2
    cur = None
    head = None

    if cur1 == None:
        return cur2
    elif cur2 == None:
        return cur1

    if cur1.val <= cur2.val:                    
        head = cur1
        cur = cur1
        cur1 = cur1.next
    else:
        head = cur2
        cur = cur2
        cur2 = cur2.next        
    
    while(cur1 != None or cur2 != None):
        # 한쪽이 끝이면 다른 쪽 값을 붙임
        if cur1 == None:
            cur.next = cur2
            return head
        elif cur2 == None:
            cur.next = cur1
            return head

        # 작은 값을 현재 값에 붙임
        if cur1.val <= cur2.val:
            cur.next = cur1
            cur1 = cur1.next
        else:
            cur.next = cur2
            cur2 = cur2.next

        cur = cur.next

    return head

Runtime: 92ms, faster than 97.35%

All Paths From Source to Target
class Solution:
    def searchGraph(self, index, graph, savedStatus):
        for node in graph[index]:
            newStatus = savedStatus + [node]

            if node == (len(graph)-1):
                self.result.append(newStatus)
            else:
                self.searchGraph(node, graph, newStatus)

    def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
        self.result = []
        self.searchGraph(0, graph, [0])

        return self.result
  • No labels