-
Notifications
You must be signed in to change notification settings - Fork 43
/
linked-list-components.py
64 lines (56 loc) · 1.5 KB
/
linked-list-components.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
# V1'
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def numComponents(self, head, G):
count = 0
G = set(G)
dummy = ListNode(-1)
dummy.next = head
cur = dummy
while cur and cur.__next__:
if cur.val not in G and cur.next.val in G:
count = count + 1
cur = cur.__next__
return count
# V2
class Solution:
def numComponents(self, head, G):
"""
:type head: ListNode
:type G: List[int]
:rtype: int
"""
groups = 0
subset = set(G)
while head:
if head.val in subset and (not head.__next__ or head.next.val not in subset):
groups += 1
head = head.__next__
return groups
# V3
# Time: O(m + n), m is the number of G, n is the number of nodes
# Space: O(m)
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def numComponents(self, head, G):
"""
:type head: ListNode
:type G: List[int]
:rtype: int
"""
lookup = set(G)
dummy = ListNode(-1)
dummy.next = head
curr = dummy
result = 0
while curr and curr.__next__:
if curr.val not in lookup and curr.next.val in lookup:
result += 1
curr = curr.__next__
return result