-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathhaklee.py
56 lines (43 loc) Β· 1.63 KB
/
haklee.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
50
51
52
53
54
55
56
"""TC: O(n*log(l)), SC: O(l)
lμ 리μ€νΈ κ°μ, nμ μ 체 μμ΄ν
κ°μ
μμ΄λμ΄:
- κ° λ¦¬μ€νΈμμ μ μΌ μμ μλ κ°μ λ½μμ μ°μ μμ νμ λ£λλ€.
- μ°μ μμ νμ μ μΌ μμ μλ κ°μ λ½μμ
- μ΄ κ°μ΄ μ΄λ 리μ€νΈμμ λμλμ§ νμΈν΄μ ν΄λΉ 리μ€νΈμ μ μΌ μμ μλ κ°μ μλ‘ λ½μμ μ°μ μμ νλ₯Ό μ±μ΄λ€.
- μ°μ μμ νμμ λ½μ κ°μ κ²°κ³Ό 리μ€νΈμ λνλ€.
SC:
- μ°μ μμ νμ μ΅λ listμ κ°μ λ§νΌμ μμ΄ν
μ‘΄μ¬ κ°λ₯. O(l).
-
TC:
- heap ν¬κΈ°λ μ΅λ lμ΄λ€.
- μ΄ heapμ μμ΄ν
μ pushνκ³ popν λ O(log(l)) μκ° μμ.
- μμ μνμ μ 체 μμ΄ν
κ°μ λ§νΌ νλ€.
- μ’
ν©νλ©΄ O(n*log(l))
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from heapq import heappush, heappop
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
heap = []
head = ListNode()
tail = head
# init
for i in range(len(lists)):
if lists[i]:
heappush(heap, (lists[i].val, i))
lists[i] = lists[i].next
# process
while heap:
v, idx = heappop(heap)
# heap λ€μ μ±μλ£κΈ°
if lists[idx]:
heappush(heap, (lists[idx].val, idx))
lists[idx] = lists[idx].next
# κ²°κ³Όλ¬Ό μ±μλ£κΈ°
tail.next = ListNode(v)
tail = tail.next
return head.next