817. Linked List Components

1. 原始题目

We are given head, the head node of a linked list containing unique integer values.

We are also given the list G, a subset of the values in the linked list.

Return the number of connected components in G, where two values are connected if they appear consecutively in the linked list.

Example 1:

Input: 
head: 0->1->2->3
G = [0, 1, 3]
Output: 2
Explanation: 
0 and 1 are connected, so [0, 1] and [3] are the two connected components.

Example 2:

Input: 
head: 0->1->2->3->4
G = [0, 3, 1, 4]
Output: 2
Explanation: 
0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.

2. 题目理解

给定一个链表(链表结点包含一个整型值)的头结点 head

同时给定列表 G,该列表是上述链表中整型值的一个子集。

返回列表 G 中组件的个数,这里对组件的定义为:链表中一段最长连续结点的值(该值必须在列表 G 中)构成的集合。

示例 1:

输入: 
head: 0->1->2->3
G = [0, 1, 3]
输出: 2
解释: 
链表中,0 和 1 是相连接的,且 G 中不包含 2,所以 [0, 1] 是 G 的一个组件,同理 [3] 也是一个组件,故返回 2。

示例 2:

输入: 
head: 0->1->2->3->4
G = [0, 3, 1, 4]
输出: 2
解释: 
链表中,0 和 1 是相连接的,3 和 4 是相连接的,所以 [0, 1] 和 [3, 4] 是两个组件,故返回 2。

注意:

  • 如果 N 是给定链表 head 的长度,1 <= N <= 10000
  • 链表中每个结点的值所在范围为 [0, N - 1]
  • 1 <= G.length <= 10000
  • G 是链表中所有结点的值的一个子集.

3. 解题

思路:对于链表每个结点若出现在列表中,则起码是一个组件了,然后继续扫描链表看是单个元素还是有连续的元素。思路还是直观比较简单了。

 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     def numComponents(self, head: ListNode, G: List[int]) -> int:
 9         p = head
10         num = 0
11         while(p):
12             if p.val in G:                            # 在当前节点已经在列表中的基础上,
13                 while p.next and p.next.val in G:     # 判断下一个连续结点是否也在,即判断该组件是单个结点还是多个呢
14                     p = p.next
15                 num += 1
16             p = p.next
17         
18         return num

验证

 1 # 新建链表1
 2 listnode1 = ListNode_handle(None)
 3 s1 = [1,2,3,4,5,6,7,8]
 4 for i in s1:
 5     listnode1.add(i)
 6     
 7 listnode1.print_node(listnode1.head)
 8 
 9 s = Solution()
10 head = s.numComponents(listnode1.head, [2,3,4,7,1])
11 print(head)

1 2 3 4 5 6 7 8
2

原文地址:https://www.cnblogs.com/king-lps/p/10668565.html