Skip to content

Commit

Permalink
solve: Merge K Sorted Lists
Browse files Browse the repository at this point in the history
  • Loading branch information
KwonNayeon committed Feb 14, 2025
1 parent 862ff81 commit b22c9ed
Showing 1 changed file with 36 additions and 5 deletions.
41 changes: 36 additions & 5 deletions merge-k-sorted-lists/KwonNayeon.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,43 @@
- lists[i] is sorted in ascending order.
- The sum of lists[i].length will not exceed 10^4
Time Complexity:
-
Time Complexity: O(N log k)
- N์€ ๋ชจ๋“  ๋…ธ๋“œ์˜ ์ด ๊ฐœ์ˆ˜, k๋Š” ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์˜ ๊ฐœ์ˆ˜
- ํž™ ์—ฐ์‚ฐ์— log k ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฌ๊ณ , ์ด๋ฅผ N๋ฒˆ ์ˆ˜ํ–‰ํ•จ
Space Complexity:
-
Space Complexity: O(k)
- ํž™์—๋Š” ํ•ญ์ƒ k๊ฐœ์˜ ๋…ธ๋“œ๋งŒ ์ €์žฅ๋จ
ํ’€์ด๋ฐฉ๋ฒ•:
1.
1. ์ตœ์†Œ ํž™์„ ์‚ฌ์šฉํ•˜์—ฌ k๊ฐœ์˜ ์ •๋ ฌ๋œ ๋ฆฌ์ŠคํŠธ๋ฅผ ํšจ์œจ์ ์œผ๋กœ ๋ณ‘ํ•ฉํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜
2. ๊ฐ ๋ฆฌ์ŠคํŠธ์˜ ์ฒซ ๋ฒˆ์งธ ๋…ธ๋“œ๋ฅผ ํž™์— ๋„ฃ๊ณ  ์‹œ์ž‘ํ•จ
3. ํž™์—์„œ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ ๊ฐ€์ง„ ๋…ธ๋“œ๋ฅผ ๊บผ๋‚ด์„œ ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€
4. ๊บผ๋‚ธ ๋…ธ๋“œ์˜ ๋‹ค์Œ ๋…ธ๋“œ๋ฅผ ๋‹ค์‹œ ํž™์— ๋„ฃ์Œ
5. ์ด ๊ณผ์ •์„ ํž™์ด ๋นŒ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•จ
Note: ์ด ๋ฌธ์ œ๋Š” ํ’€๊ธฐ ์–ด๋ ค์›Œ์„œ ํ’€์ด๋ฅผ ๋ณด๊ณ  ๊ณต๋ถ€ํ–ˆ์Šต๋‹ˆ๋‹ค. ๋ณต์Šต ํ•„์ˆ˜
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
min_heap = []

for i, l in enumerate(lists):
if l:
heapq.heappush(min_heap, (l.val, i, l))

head = point = ListNode(0)

while min_heap:
val, i, node = heapq.heappop(min_heap)
point.next = node
point = point.next

if node.next:
heapq.heappush(min_heap, (node.next.val, i, node.next))

return head.next

0 comments on commit b22c9ed

Please sign in to comment.