给定一个链表(链表结点包含一个整型值)的头结点 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 是链表中所有结点的值的一个子集.
解答1:

public int numComponents(ListNode head, int[] G) { /*用一个集合把数组里的元素存起来*/ Set<Integer> integers = new HashSet<>(G.length); for (int i = 0; i < G.length; i++) { integers.add(G[i]); } /*组件数量*/ int num = 0; /*定义一个哑节点*/ ListNode dumb = new ListNode(0); dumb.next = head; /*偏移指针指向头*/ this.offset = head; /*起始指针指向哑节点*/ this.start = dumb; while (offset != null) { /*当前节点的值不在数组中时判断起始节点的下一个节点是不是偏移节点,如果不是则组件数量加1同时起始节点指向偏移节点*/ if (!integers.contains(offset.val)) { if (start.next != offset) { num++; } start = offset; } /*偏移节点指向自己的下一个节点*/ offset = offset.next; } /*判断链表的尾节点是否是一个单独的组件*/ if (start.next != null) { num++; } return num; } /** * 起始节点 */ private ListNode start; /** * 偏移节点 */ private ListNode offset;
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-components