LC 817. 链表组件

题目描述

这是 LeetCode 上的 817. 链表组件 ,难度为 中等

给定链表头结点 head,该链表上的每个结点都有一个 唯一的整型值 。同时给定列表 nums,该列表是上述链表中整型值的一个子集。

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

示例 1:

1
2
3
4
5
输入: head = [0,1,2,3], nums = [0,1,3]

输出: 2

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

示例 2:

1
2
3
4
5
输入: head = [0,1,2,3,4], nums = [0,3,1,4]

输出: 2

解释: 链表中,0 和 1 是相连接的,3 和 4 是相连接的,所以 [0, 1][3, 4] 是两个组件,故返回 2。

提示:

  • 链表中节点数为 n
  • $1 <= n <= 10^4$
  • $0 <= Node.val < n$
  • Node.val 中所有值 不同
  • $1 <= nums.length <= n$
  • $0 <= nums[i] < n$
  • nums 中所有值 不同

模拟

根据题意进行模拟即可 : 为了方便判断某个 $node.val$ 是否存在于 nums 中,我们先使用 Set 结构对所有的 $nums[i]$ 进行转存,随后每次检查连续段(组件)的个数。

Java 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int numComponents(ListNode head, int[] nums) {
int ans = 0;
Set<Integer> set = new HashSet<>();
for (int x : nums) set.add(x);
while (head != null) {
if (set.contains(head.val)) {
while (head != null && set.contains(head.val)) head = head.next;
ans++;
} else {
head = head.next;
}
}
return ans;
}
}

TypeScript 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function numComponents(head: ListNode | null, nums: number[]): number {
let ans = 0
const set = new Set<number>()
for (const x of nums) set.add(x)
while (head != null) {
if (set.has(head.val)) {
while (head != null && set.has(head.val)) head = head.next
ans++
} else {
head = head.next
}
}
return ans
}

Python 代码:
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int:
ans = 0
nset = set([x for x in nums])
while head:
if head.val in nset:
while head and head.val in nset:
head = head.next
ans += 1
else:
head = head.next
return ans

  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$

最后

这是我们「刷穿 LeetCode」系列文章的第 No.817 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。

在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。

为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode

在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。