본문 바로가기
PROGRAMMING/LeetCode

[Leetcode] 24. Swap Nodes in Pairs_해설, 풀이, 설명

by HYUNHP 2023. 5. 26.
반응형

안녕하세요, HELLO

 

오늘은 Leetcode 알고리즘 문제 '24. Swap Nodes in Pairs'에 대해서 살펴보고자 합니다. 

 

알고리즘 문제, 코드, 해설 그리고 Leetcode에서 제공해준 solution 순서대로 정리하였습니다.


STEP 1. 'Swap Nodes in Pairs' 알고리즘 문제

 

STEP 2. 'Swap Nodes in Pairs' 코드(code)

 

STEP 3. 'Swap Nodes in Pairs' 해설

 

STEP 4. 'Swap Nodes in Pairs' solution

 

반응형

 

STEP 1. 'Swap Nodes in Pairs' 알고리즘 문제

 

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

 

주어진 연결 리스트의 메번 연결된 2개의 노드의 순서를 서로 바꿉니다. 데이터의 수정없이 순서 변경만으로 문제를 해결해야 됩니다.

 

Constraints:

  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100


STEP 2. 'Swap Nodes in Pairs' 코드(code)

 

■ Runtime: 51 ms. Beats: 27.3%
■ Beats: 16.3 MB. Beats :62.64%

 

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        temp_lst = []

        while head :
            temp_lst.append(head.val)
            head = head.next

        check_lst = []

        for index in range(0, (len(temp_lst))//2):
            check_lst.append(temp_lst[(2 * index) +1])
            check_lst.append(temp_lst[(2 * index)])

        # ODD CASE
        if len(temp_lst)%2 == 1:
            check_lst.append(temp_lst[-1])

        check_lst = check_lst[::-1]
        final = None
        for value in check_lst:
            final = ListNode(value, final)

        return final

STEP 3. 'Swap Nodes in Pairs' 해설

 

[2n, 2n+1]의 순서를 [2n+1, 2n]으로 바꾸는 문제로서, 연결 리스트의 개수를 1/2으로 나눠서 서로 순서를 바꿔서 계산했습니다. 이때, 홀수인 경우는 맨 마지막 숫자를 리스트에 추가하여서 해결했습니다. 

 

Leetcode 대표 해설은 두 번째 그리고 세 번째 연결 데이터 유무를 확인하고, 데이터가 모두 있는 경우에 [a,b,c] 순서를 [b, a, c]로 변경하여, 순서 변경과 홀수 경우를 해결했습니다.

 

728x90

 

STEP 4. 'Swap Nodes in Pairs' solution

 

추가적으로, Leetcode에서 제공해준 solution 코드를 살펴보겠습니다.

 

■ Runtime: 46 ms. Beats 52.96%
Beats: 16.4 MB. Beats 20.50%

 

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:

        dummy = prev = ListNode(0)
        prev.next = head
		
        while prev.next and prev.next.next:
            a = prev.next
            b = prev.next.next
            c = prev.next.next.next
            prev.next = b
            prev.next.next = a
            prev.next.next.next = c
            prev = prev.next.next
        return dummy.next

■ 마무리

 

오늘은 Leetcode 알고리즘 문제 '24. Swap Nodes in Pairs'에 대해서 알아봤습니다.

좋아요와 댓글 부탁드리며,

오늘 하루도 즐거운 날 되시길 기도하겠습니다 :)

감사합니다.

반응형

댓글