-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathKwonNayeon.py
49 lines (40 loc) ยท 1.62 KB
/
KwonNayeon.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"""
Constraints:
- k == lists.length
- 0 <= k <= 10^4
- 0 <= lists[i].length <= 500
- -10^4 <= lists[i][j] <= 10^4
- lists[i] is sorted in ascending order.
- The sum of lists[i].length will not exceed 10^4
Time Complexity: O(N log k)
- N์ ๋ชจ๋ ๋
ธ๋์ ์ด ๊ฐ์, k๋ ์ฐ๊ฒฐ ๋ฆฌ์คํธ์ ๊ฐ์
- ํ ์ฐ์ฐ์ log k ์๊ฐ์ด ๊ฑธ๋ฆฌ๊ณ , ์ด๋ฅผ N๋ฒ ์ํํจ
Space Complexity: O(k)
- ํ์๋ ํญ์ k๊ฐ์ ๋
ธ๋๋ง ์ ์ฅ๋จ
ํ์ด๋ฐฉ๋ฒ:
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