leetcode817 Linked List Components

 1 """
 2 We are given head, the head node of a linked list containing unique integer values.
 3 
 4 We are also given the list G, a subset of the values in the linked list.
 5 
 6 Return the number of connected components in G, where two values are connected if they appear consecutively in the linked list.
 7 
 8 Example 1:
 9 
10 Input: 
11 head: 0->1->2->3
12 G = [0, 1, 3]
13 Output: 2
14 Explanation: 
15 0 and 1 are connected, so [0, 1] and [3] are the two connected components.
16 
17 Example 2:
18 
19 Input: 
20 head: 0->1->2->3->4
21 G = [0, 3, 1, 4]
22 Output: 2
23 Explanation: 
24 0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.
25 
26 """
27 class Solution:
28     def numComponents(self, head, G):
29         set_G = set(G)  #试了用list也能通过,set是为了规范数据集
30         p = head
31         count =0
32         while(p):
33             if p.val in set_G and (p.next == None or p.next!=None and p.next.val not in set_G):
34                 #!!!if条件句关键
35                 #将G中的元素放入set 或者字典中用于查找。
36                 # 遍历链表, 链表中的元素被计数的条件是,
37                 # 如果当前元素在G中且下一个元素不在G中(或者为None),
38                 # 那么当前的元素属于一个component。
39                 count += 1
40             p = p.next
41         return count
原文地址:https://www.cnblogs.com/yawenw/p/12250468.html