파비의 매일매일 공부기록

2023.09.06 Today's Challenge 본문

Problem Solving/LeetCode

2023.09.06 Today's Challenge

fabichoi 2023. 9. 6. 23:45

https://leetcode.com/problems/split-linked-list-in-parts/

 

Split Linked List in Parts - LeetCode

Can you solve this real interview question? Split Linked List in Parts - Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts. The length of each part should be as equal as possible: no two par

leetcode.com

리스트의 연속

class Solution:
    def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:
        cur = head
        for n in range(1001):
            if not cur:
                break
            cur = cur.next
        width, remainder = divmod(n, k)

        ans = []
        cur = head
        for i in range(k):
            head = write = ListNode(None)
            for j in range(width + (i < remainder)):
                write.next = write = ListNode(cur.val)
                if cur:
                    cur = cur.next
            ans.append(head.next)
        return ans
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.09.08 Today's Challenge  (0) 2023.09.08
2023.09.07 Today's Challenge  (0) 2023.09.07
2023.09.05 Today's Challenge  (0) 2023.09.05
2023.09.04 Today's Challenge  (0) 2023.09.04
2023.09.03 Today's Challenge  (0) 2023.09.03
Comments