-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathdusunax.py
70 lines (58 loc) ยท 2.06 KB
/
dusunax.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
'''
# 19. Remove Nth Node From End of List
## ํ์ด ์ ๊ทผ๋ฐฉ์ ๋ ํผ๋ฐ์ค
- https://www.algodale.com/problems/remove-nth-node-from-end-of-list/
'''
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
'''
# 1. ๋
ธ๋ ๋ฆฌ์คํธ
- ์์ ์ธ๋ฑ์ค ์์ ์ ๊ทผ
- nodes ๋ฐฐ์ด์ ์ฌ์ฉํ์ฌ ๋ง์ง๋ง n๋ฒ์งธ ๋
ธ๋๋ฅผ ์ฐพ๋๋ค.
- ๋ฉ๋ชจ๋ฆฌ ๋ญ๋น
TC: O(N), SC: O(N)
'''
# nodes = [] # ๋ฐฐ์ด
# temp = ListNode(None, head)
# node = temp
# while node:
# nodes.append(node)
# node = node.next
# nodes[-n - 1].next = nodes[-n - 1].next.next
# return temp.next
'''
# 2. ํ
- ํ๋ฅผ ์ฌ์ฉํ์ฌ ๋ง์ง๋ง n๋ฒ์งธ ๋
ธ๋๋ฅผ ์ฐพ๋๋ค.
- ์ต๋ n+1๊ฐ์ ๋
ธ๋(ํ์ํ ๋ฒ์)๋ง ์ ์ง, ์ฌ๋ผ์ด๋ฉ ์๋์ฐ
TC: O(N), SC: O(N)
'''
# queue = deque() #ํ
# temp = ListNode(None, head)
# node = temp
# for _ in range(n + 1):
# queue.append(node)
# node = node.next
# while node:
# queue.popleft()
# queue.append(node)
# node = node.next
# queue[0].next = queue[0].next.next
# return temp.next
'''
# 3. ํฌ์ธํฐ
- ์ฐ๊ฒฐ ๋ฆฌ์คํธ์ ํน์ฑ ์ด์ฉ
- ์ฒซ๋ฒ์งธ ํฌ์ธํฐ๋ n๋ฒ ์ด๋ํ์ฌ ๋ง์ง๋ง ๋
ธ๋๋ฅผ ์ฐพ๋๋ค.
- ๋๋ฒ์งธ ํฌ์ธํฐ๋ ์ฒซ๋ฒ์งธ ํฌ์ธํฐ๊ฐ ๋ง์ง๋ง ๋
ธ๋๋ฅผ ์ฐพ์ ๋๊น์ง ์ด๋ํ๋ค.
- ๋๋ฒ์งธ ํฌ์ธํฐ๋ ์ฒซ๋ฒ์งธ ํฌ์ธํฐ๊ฐ ๋ง์ง๋ง ๋
ธ๋๋ฅผ ์ฐพ์ผ๋ฉด ์ฒซ๋ฒ์งธ ํฌ์ธํฐ์ ์ด์ ๋
ธ๋๋ฅผ ์ญ์ ํ๋ค.
TC: O(N), SC: O(1)
'''
first = head
for _ in range(n):
first = first.next
temp = ListNode(None, head)
second = temp
while first:
first = first.next
second = second.next
second.next = second.next.next
return temp.next