1、 题目介绍:给定链表头结点 head,该链表上的每个结点都有一个唯一的整型值。同时给定列表 nums,该列表是上述链表中整型值的一个子集。返回列表 nums 中组件的个数,这里对组件的定义为:链表中一段最长连续结点的值(该值必须在列表 nums 中)构成的集合。 * * 示例 1: * 0 -> 1 -> 2 -> 3 * 输入: head = [0,1,2,3], nums = [0,1,3] * 输出: 2 * 解释: 链表中,0 和 1 是相连接的,且 nums 中不包含 2,所以 [0, 1] 是 nums 的一个组件,同理 [3] 也是一个组件,故返回 2。 * * 示例 2: * 0 -> 1 -> 2 -> 3 -> 4 * 输入: head = [0,1,2,3,4], nums = [0,3,1,4] * 输出: 2 * 解释: 链表中,0 和 1 是相连接的,3 和 4 是相连接的,所以 [0, 1] 和 [3, 4] 是两个组件,故返回 2。
2、解题思路为:
先把nums搞成哈希表。然后遍历链表。 遍历到3、在哈希表里有,遍历到6、在哈希表里有,遍历到7没有了。好的。找到一个组件:3 -> 6 接着7遍历:遍历到9、在哈希表里有,遍历到0、在哈希表里有,遍历到6、在哈希表里有,遍历到4没有了。又一个组件。 一共2个组件。
3、具体代码:
public class ListNode {
ListNode next;
int val;
public ListNode(int val) {
this.val = val;
}
}
public class Test3 {
public static void main(String[] args) {
int[] nums = {0,1,3};
ListNode head = new ListNode(0);
head.next = new ListNode(1);
head.next.next = new ListNode(2);
head.next.next.next = new ListNode(3);
}
public static int numComponents(ListNode head, int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int ans = 0;
while (head != null) {
if (set.contains(head.val)) {
ans++;
head = head.next;
while (head != null && set.contains(head.val)) {
head = head.next;
}
} else {
head = head.next;
}
}
return ans;
}
}