Published:
Updated:

  • Reference
  • ์‹œ๊ฐ„๋ณต์žก๋„: $O(N)$
  • Runtime 39ms
  • Beats 61.73%


Solution

# Definition for singly-linked list.
from typing import Optional


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    # list1์˜ ๋ ๋…ธ๋“œ๋ฅผ ์•Œ์•„์•ผ ๋จ (null์ผ ๋•Œ๊นŒ์ง€ ์ด๋™ํ•ด์•ผ ๋˜๋‹ˆ)
    # ์ฒ˜์Œ์€ ํฌ์ธํ„ฐ๊ฐ€ ๊ฐ๊ฐ ์ฒ˜์Œ์„ ๊ฐ€๋ฆฌํ‚ค๊ฒŒ ํ•จ
    # ์ž‘์€ ๊ฐ’์„ ๋‹ด๊ณ  ์žˆ๋Š” ๋…ธ๋“œ๋ฅผ ์ถ”๊ฐ€ํ•˜๊ณ , ํฌ์ธํ„ฐ๋ฅผ ๋‹ค์Œ ๋…ธ๋“œ๋กœ ์ „์ง€๋‹›ํ‚ด
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        # dummy: LinkedList์—์„œ ์ž์ฃผ ์‚ฌ์šฉ๋จ (๊ฒฝ๊ณ„ ์กฐ๊ฑด์„ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฐ ํ›จ์”ฌ ์ˆ˜์›”ํ•ด์ง)
        dummy = ListNode()
        end = dummy

        # Example 2, 3 ์ฒ˜๋ฆฌ
        if list1 is None:
            return list2

        if list2 is None:
            return list1

        # ๋‘˜ ๋‹ค null์ด ์•„๋‹ ๋•Œ
        while list1 is not None and list2 is not None:
            if list1.val < list2.val:
                end.next = list1  # list1์ด ๋ณ‘ํ•ฉ๋œ ๋‹ค์Œ ๋…ธ๋“œ
                list1 = list1.next  # ๋‹ค์Œ ๋…ธ๋“œ๋กœ ํฌ์ธํ„ฐ ์ด๋™
            else:  # list.val >= list2.val
                end.next = list2  # list2์ด ๋ณ‘ํ•ฉ๋œ ๋‹ค์Œ ๋…ธ๋“œ
                list2 = list2.next  # ๋‹ค์Œ ๋…ธ๋“œ๋กœ ํฌ์ธํ„ฐ ์ด๋™

            # ์—…๋ฐ์ดํŠธ๋ฅผ ํ•ด์ค˜์•ผ ๋ณ‘ํ•ฉ๋œ ๊ฒƒ๋„ ์ด๋™ํ•ด์ฃผ์ง€
            end = end.next

        # while๋ฌธ์„ ๋น ์ ธ๋‚˜์™”๋‹ค๋Š” ๊ฒƒ์€ list1, list2 ๋‘˜ ์ค‘ ํ•˜๋‚˜๊ฐ€ null์ด๋ผ๋Š” ๊ฒƒ
        # null์ด ์•„๋‹Œ ์ชฝ์— ์žˆ๋Š” list์˜ ๋‚จ์€ ๋…ธ๋“œ๋ฅผ ๋ณ‘ํ•ฉ๋œ ๊ฒƒ์— ์ถ”๊ฐ€
        end.next = list1 or list2
        # ์•„๋ž˜ ์ฝ”๋“œ๋ฅผ ์œ„์˜ ์ฝ”๋“œ์ฒ˜๋Ÿผ ์ค„์—ฌ ์“ธ ์ˆ˜ ์žˆ์Œ
        # if list1:
        #     end.next = list1
        # elif list2:
        #     end.next = list2

        return dummy.next

Leave a comment