[Leetcode] 143. Reorder List

Sungwooยท2024๋…„ 11์›” 19์ผ
0

Algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
15/43
post-thumbnail

๐Ÿ“•๋ฌธ์ œ

[Leetcode] 143. Reorder List

๋ฌธ์ œ ์„ค๋ช…

์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์˜ ์ˆœ์„œ๋ฅผ ์ฃผ์–ด์ง„ ๊ทœ์น™๋Œ€๋กœ ์žฌ๋ฐฐ์น˜ํ•˜๋Š” ๋ฌธ์ œ๋‹ค. ๊ทœ์น™์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.
[1, 2, 3, 4, 5 ... n-2, n-1, n]์„ ์žฌ๋ฐฐ์น˜ํ•˜๋ฉด [1, n, 2, n-1, 3, n-2 ...]์ด ๋œ๋‹ค.

์˜ˆ๋ฅผ๋“ค์–ด [1, 2, 3, 4, 5]๋ฅผ ์žฌ๋ฐฐ์น˜ํ•˜๋ฉด [1, 5, 2, 4, 3]์ด ๋œ๋‹ค.


๐Ÿ“ํ’€์ด

deque

from collections import deque
class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        deq = deque()
        cursor = head
        while cursor.next:
            deq.append(cursor.next)
            cursor = cursor.next
        cursor = head
        count = 0
        while deq:
            if count % 2 == 0:
                cursor.next = deq.pop()
            else:
                cursor.next = deq.popleft()
            cursor = cursor.next
            count += 1
        cursor.next = None
  • deque๋ฅผ ์ƒ์„ฑํ•ด ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์˜ ๋…ธ๋“œ๋“ค์„ ์ˆœ์„œ๋Œ€๋กœ ์ง‘์–ด๋„ฃ๋Š”๋‹ค.
  • ์•ž์—์„œ๋ถ€ํ„ฐ, ๋’ค์—์„œ๋ถ€ํ„ฐ ๋ฒˆ๊ฐˆ์•„ ์ด์–ด์•ผ ํ•˜๋ฏ€๋กœ count๋ฅผ ํ†ตํ•ด ๊ฒฝ์šฐ๋ฅผ ๋‚˜๋ˆด๋‹ค.
    • count๊ฐ€ ์ง์ˆ˜์ธ ๊ฒฝ์šฐ deque์—์„œ ๊ฐ€์žฅ ๋์˜ ์š”์†Œ๋ฅผ ๊บผ๋‚ด๊ณ  cursor์— ์—ฐ๊ฒฐ์‹œํ‚จ๋‹ค.
    • count๊ฐ€ ํ™€์ˆ˜์ธ ๊ฒฝ์šฐ deque์—์„œ ๊ฐ€์žฅ ์•ž์˜ ์š”์†Œ๋ฅผ ๊บผ๋‚ด๊ณ  cursor์— ์—ฐ๊ฒฐ์‹œํ‚จ๋‹ค.
  • ๋ชจ๋“  ์—ฐ๊ฒฐ์ด ๋๋‚˜๋ฉด ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ์˜ next๊ฐ’์„ None์œผ๋กœ ์„ค์ •ํ•œ๋‹ค.


Runtime์ด ์•„์‰ฌ์›Œ ๋‹ค๋ฅธ ํ’€์ด๋ฅผ ์ฐพ์•„๋ณด๋˜ ์ค‘ ํˆฌํฌ์ธํ„ฐ๋ฅผ ์ด์šฉํ•ด ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์˜ ์ค‘๊ฐ„ ๋…ธ๋“œ๋ฅผ ์ฐพ๊ณ , ๋‘ ๊ฐœ์˜ ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ๋กœ ๋‚˜๋ˆˆ ๋’ค ํ•ด๊ฒฐํ•˜๋Š” ํ’€์ด๋ฅผ ๋ฐœ๊ฒฌํ–ˆ๋‹ค.(Leetcode์˜ Code Sample)

class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        slow = fast = head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        second = slow.next
        slow.next = None
        prev = None
        while second:
            tmp = second.next
            second.next = prev
            prev = second
            second = tmp
        second = prev
        first = head

        while second:
            first_temp = first.next
            first.next = second
            second_temp = second.next
            second.next = first_temp
            second = second_temp
            first = first_temp
  • ํ•œ ๋ฒˆ์— ํ•œ์นธ์”ฉ ์ด๋™ํ•˜๋Š” slow, ๋‘์นธ์”ฉ ์ด๋™ํ•˜๋Š” fast ํฌ์ธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•ด ์ค‘๊ฐ„ ๋…ธ๋“œ๋ฅผ ์ฐพ๋Š”๋‹ค.
  • ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ๋Š” ๋‘๊ฐœ๋กœ ๋‚˜๋‰œ๋‹ค. ์ ˆ๋ฐ˜ ๊ธฐ์ค€์œผ๋กœ ์•ž์˜ ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ first์™€ ๋’ค์˜ ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ second
  • ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ second๋ฅผ ์—ญ์ˆœ์œผ๋กœ ๋’ค์ง‘๋Š”๋‹ค.
  • first์™€ second์˜ ์š”์†Œ๋ฅผ ๋ฒˆ๊ฐˆ์•„๊ฐ€๋ฉฐ ์ด์œผ๋ฉฐ ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ๋ฅผ ์žฌ๋ฐฐ์น˜ํ•œ๋‹ค.

Runtime์ด ์ค„์—ˆ๋‹ค!
deque์—์„œ ๋…ธ๋“œ๋ฅผ ์‚ฝ์ž…/์‚ญ์ œํ•˜๋Š” ๊ณผ์ •์ด ์—†์–ด์ ธ์„œ ๊ทธ๋Ÿฐ ๊ฒƒ ๊ฐ™๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€