We are given head

原题展示

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.

首先,在拿到这个题目时,直呼一句好家伙,然后启动浏览器翻译结果(翻译过程就不做赘述,有手就行),同时,在翻译结束后再根据题目的意思,基本可以总结出以下四点

1.如果 N 是给定链表 head 的长度,1 <= N <= 10000

2.链表中每个结点的值所在范围为 [0, N - 1]

3.1 <= G.length <= 10000

4.G 是链表中所有结点的值的一个子集

显而易见,代码求解结果如下

 其实,在这个题目中,自己遇到的问题就是,在考虑WHILE语句时,一开始没有办法考虑充分,后来在报错之后,明白其实对于链表每个结点若出现在列表中的情况,只需要继续扫描链表看是单个元素还是有连续的元素,在当前节点已经在列表中的基础上,判断下一个连续结点是否也在,即判断该组件是单个结点还是多个即可。

jsj201 zhong

猜你喜欢

转载自blog.csdn.net/zjsru_Beginner/article/details/119969153
we