21. Merge Two Sorted Lists Python3

Yelim Kim·2021년 9월 18일
0

Python Algorithm Interview

목록 보기
11/36
post-thumbnail

Problem

Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.

Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:

Input: l1 = [], l2 = []
Output: []

Example 3:

Input: l1 = [], l2 = [0]
Output: [0]

Constraints:

The number of nodes in both lists is in the range [0, 50].
-100 <= Node.val <= 100
Both l1 and l2 are sorted in non-decreasing order.

My code

Definition for singly-linked list.

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
        
class Solution:
    def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        result = ListNode()
        current = result
        
        while l1 and l2 : 
            if l1.val < l2.val : 
                current.next = l1 
                l1 = l1.next 
            else:
                current.next = l2
                l2 = l2.next
            current = current.next
        if l1 : 
            current.next = l1
        elif l2:
            current.next = l2
        return result.next

Review

[실행 결과]
Runtime: 36 ms / Memory: 14.4MB

[접근법]
l1과 l2의 맨 앞 값을 비교한다.
작은 값을 current에 저장하고 해당 리스트를 하나 줄인다. ->이 과정을 리스트 하나가 없어질때까지 반복한다.
하나가 없어진 후 남은 리스트 하나를 current에 추가한다.
출력한다.

[느낀점]
두 연결 리스트를 합하고 정렬하려고 했는데 합하는 과정에서 동시에 비교를 할 수 있었다.
연결 리스트를 .head나 .tail을 쓰지 않고 구현하는게 너무 힘들었다... 최소한으로 쓸 수 있는 코드를 생각하고 구현하자. 쉽게 생각하려다 코드가 더 복잡해진다....

profile
뜬금없지만 세계여행이 꿈입니다.

0개의 댓글