-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0817-linked-list-components.py
More file actions
40 lines (34 loc) · 1008 Bytes
/
0817-linked-list-components.py
File metadata and controls
40 lines (34 loc) · 1008 Bytes
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
# time complexity: O(n)
# space complexity: O(n)
from typing import List, Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int:
numsSet = set(nums)
node = head
inNumSet = False
result = 0
while node:
if node.val in numsSet:
if not inNumSet:
inNumSet = True
result += 1
else:
inNumSet = False
node = node.next
return result
head1 = ListNode(0)
head1.next = ListNode(1)
head1.next.next = ListNode(2)
head1.next.next.next = ListNode(3)
nums = [0, 1, 3]
print(Solution().numComponents(head1, nums))
head2 = ListNode(0)
head2.next = ListNode(1)
head2.next.next = ListNode(2)
head2.next.next.next = ListNode(3)
head2.next.next.next.next = ListNode(4)
print(Solution().numComponents(head2, nums))