-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add solution: remove-nth-node-from-end-of-list
- Loading branch information
Showing
1 changed file
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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 |