forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEgonD3V.py
91 lines (72 loc) ยท 2.21 KB
/
EgonD3V.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
from typing import Optional
from unittest import TestCase, main
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def values(self) -> [int]:
result = []
node = self
while node:
result.append(node.val)
node = node.next
return result
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
return self.solve_two_pointer(head, n)
"""
Runtime: 0 ms (Beats 100.00%)
Time Complexity: O(n)
> list์ ๋ชจ๋ node + dummy node๋ฅผ ํ์ํ๋ฏ๋ก O(n + 1) ~= O(n)
Memory: 16.62 MB (Beats 15.78%)
Space Complexity: O(1)
> ํฌ์ธํฐ๋ง ์ฌ์ฉํ๋ฏ๋ก O(1)
"""
def solve_two_pointer(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
if head.next is None:
return None
dummy = ListNode(-1)
dummy.next = head
head = dummy
slow = fast = head
while n:
if fast.next:
fast = fast.next
n -= 1
while fast is not None:
if fast.next is None:
slow.next = slow.next.next
break
else:
slow = slow.next
fast = fast.next
return head.next
class _LeetCodeTestCases(TestCase):
def test_1(self):
node_1 = ListNode(1)
node_2 = ListNode(2)
node_3 = ListNode(3)
node_4 = ListNode(4)
node_5 = ListNode(5)
node_1.next = node_2
node_2.next = node_3
node_3.next = node_4
node_4.next = node_5
n = 2
output = [1, 2, 3, 5]
self.assertEqual(Solution().removeNthFromEnd(node_1, n).values(), output)
def test_2(self):
node_1 = ListNode(1)
n = 1
output = []
self.assertEqual(Solution().removeNthFromEnd(node_1, n).values(), output)
def test_3(self):
node_1 = ListNode(1)
node_2 = ListNode(2)
node_1.next = node_2
n = 2
output = [2]
self.assertEqual(Solution().removeNthFromEnd(node_1, n).values(), output)
if __name__ == '__main__':
main()