IT/자기계발 ( Leetcode )

2021-01-05] Merge Two Sorted Lists

Bell_bear 2021. 1. 5. 03:05
반응형

오늘의 문제:

leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/579/week-1-january-1st-january-7th/3592/

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com

 

이번엔 그래도 바로 이해가능한 문제가 나왔다! 제목처럼 두개의 Input List를 오름 차순으로 합친 하나의 List 만들기!

 

그래도 예시를 보며 다시 한번 이해해보자.

 

<예시 1-3>

주어지는 ListNode 2개를 하나의 정렬된 ListNode로 만들어 반환하는 내요인 것을 알 수있다.

 

이렇게 그림이나, 설명이 쉬워서 문제가 이해가 잘되면 빨리 풀 수 있을 텐데ㅋㅋㅋ 그러면 어떻게 풀어야할까?

 

예시에서 보이는 것 처럼 List로 주는 것이 아니고 ListNode인 것이다. 데이터의 순서를 바꾸는것엔 역시

List만한게 없어서 두개의 ListNode를 우선 하나의 List로 만들고 정렬한 다음, 그 List를 ListNode로 변환하자!

 

문제풀이)

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution(object):

    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        ans=[]
        while l1:
            ans.append(l1.val) # Input ListNode #1을 List화 
            l1=l1.next
        while l2:
            ans.append(l2.val) # Input ListNode #2을 List화 
            l2=l2.next
        
        sort_ans=sorted(ans) # 합쳐진 List를 정렬
        anslist=None
        for i in sort_ans:
            if anslist == None:
                anslist=ListNode(i) # 정렬된 List에서 값을 뽑아 하나씩 ListNode화 시키기
            else:
                newlist=ListNode(i) # ListNode의 끝으로 가서 append 하는 코드
                temp=anslist
                while temp.next!=None:
                    temp=temp.next
                temp.next = newlist
        return anslist
반응형