Skip to content

Commit b22c9ed

Browse files
committed
solve: Merge K Sorted Lists
1 parent 862ff81 commit b22c9ed

File tree

1 file changed

+36
-5
lines changed

1 file changed

+36
-5
lines changed

โ€Žmerge-k-sorted-lists/KwonNayeon.py

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,43 @@
77
- lists[i] is sorted in ascending order.
88
- The sum of lists[i].length will not exceed 10^4
99
10-
Time Complexity:
11-
-
10+
Time Complexity: O(N log k)
11+
- N์€ ๋ชจ๋“  ๋…ธ๋“œ์˜ ์ด ๊ฐœ์ˆ˜, k๋Š” ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ์˜ ๊ฐœ์ˆ˜
12+
- ํž™ ์—ฐ์‚ฐ์— log k ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฌ๊ณ , ์ด๋ฅผ N๋ฒˆ ์ˆ˜ํ–‰ํ•จ
1213
13-
Space Complexity:
14-
-
14+
Space Complexity: O(k)
15+
- ํž™์—๋Š” ํ•ญ์ƒ k๊ฐœ์˜ ๋…ธ๋“œ๋งŒ ์ €์žฅ๋จ
1516
1617
ํ’€์ด๋ฐฉ๋ฒ•:
17-
1.
18+
1. ์ตœ์†Œ ํž™์„ ์‚ฌ์šฉํ•˜์—ฌ k๊ฐœ์˜ ์ •๋ ฌ๋œ ๋ฆฌ์ŠคํŠธ๋ฅผ ํšจ์œจ์ ์œผ๋กœ ๋ณ‘ํ•ฉํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜
19+
2. ๊ฐ ๋ฆฌ์ŠคํŠธ์˜ ์ฒซ ๋ฒˆ์งธ ๋…ธ๋“œ๋ฅผ ํž™์— ๋„ฃ๊ณ  ์‹œ์ž‘ํ•จ
20+
3. ํž™์—์„œ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ ๊ฐ€์ง„ ๋…ธ๋“œ๋ฅผ ๊บผ๋‚ด์„œ ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€
21+
4. ๊บผ๋‚ธ ๋…ธ๋“œ์˜ ๋‹ค์Œ ๋…ธ๋“œ๋ฅผ ๋‹ค์‹œ ํž™์— ๋„ฃ์Œ
22+
5. ์ด ๊ณผ์ •์„ ํž™์ด ๋นŒ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•จ
23+
24+
Note: ์ด ๋ฌธ์ œ๋Š” ํ’€๊ธฐ ์–ด๋ ค์›Œ์„œ ํ’€์ด๋ฅผ ๋ณด๊ณ  ๊ณต๋ถ€ํ–ˆ์Šต๋‹ˆ๋‹ค. ๋ณต์Šต ํ•„์ˆ˜
1825
"""
26+
# Definition for singly-linked list.
27+
# class ListNode:
28+
# def __init__(self, val=0, next=None):
29+
# self.val = val
30+
# self.next = next
31+
class Solution:
32+
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
33+
min_heap = []
34+
35+
for i, l in enumerate(lists):
36+
if l:
37+
heapq.heappush(min_heap, (l.val, i, l))
38+
39+
head = point = ListNode(0)
40+
41+
while min_heap:
42+
val, i, node = heapq.heappop(min_heap)
43+
point.next = node
44+
point = point.next
45+
46+
if node.next:
47+
heapq.heappush(min_heap, (node.next.val, i, node.next))
48+
49+
return head.next

0 commit comments

Comments
ย (0)