方法1
将G中的元素放入set 或者字典中用于查找。遍历链表, 链表中的元素被计数的条件是,如果当前元素在G中且下一个元素不在G中(或者为None),那么当前的元素属于一个component。
class Solution:
def numComponents(self, head: ListNode, G: List[int]) -> int:
set_G = set(G)
p = head
count =0
while(p):
if p.val in set_G and (p.next == None or p.next!=None and p.next.val not in set_G):
count +=1
p = p.next
return count
方法2
当然也可以判断当前是否为不在G中下一个是否在G中,但是这样做得讨论一下特殊的情况 ,如果head.val不在G中,那么找到的count就是我们最总想要的count,如果head在G中,那么找到的count需要+1 。
x A x B和 A x B 的区别,这两个结果都是2,但是对于AxB,我们计算出的count =1
class Solution:
def numComponents(self, head: ListNode, G: List[int]) -> int:
set_G = set(G)
count = 0
p = head
while(p):
if p.val not in set_G and (p.next and p.next.val in set_G):
count+=1
p = p.next
return count+1 if head.val in set_G else count