leetcode817 Linked List Components

Posted yawenw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

以上是关于leetcode817 Linked List Components的主要内容,如果未能解决你的问题,请参考以下文章

817. Linked List Components - LeetCode

LeetCode 817. Linked List Components (链表组件)

LeetCode 817. 链表组件

817. Linked List Components

817. Linked List Components - Medium

算法分析如何理解快慢指针?判断linked list中是否有环找到环的起始节点位置。以Leetcode 141. Linked List Cycle, 142. Linked List Cycl(代码