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

Input: head =[0,1,2,3,4], nums =[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.
We want to count contiguous segments in the linked list where all nodes’ values are in the given set nums. By using a hash set for quick lookup, we can traverse the list and count the start of each new component.
classSolution {
publicintnumComponents(ListNode head, int[] nums) {
Set<Integer> set =new HashSet<>();
for (int n : nums) set.add(n);
int ans = 0;
while (head !=null) {
if (set.contains(head.val) && (head.next==null||!set.contains(head.next.val)))
ans++;
head = head.next;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funnumComponents(head: ListNode?, nums: IntArray): Int {
val set = nums.toHashSet()
var ans = 0var node = head
while (node !=null) {
if (set.contains(node.`val`) && (node.next ==null|| !set.contains(node.next.`val`)))
ans++ node = node.next
}
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defnumComponents(self, head: Optional[ListNode], nums: list[int]) -> int:
s = set(nums)
ans =0while head:
if head.val in s and (not head.next or head.next.val notin s):
ans +=1 head = head.next
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnnum_components(head: Option<Box<ListNode>>, nums: Vec<i32>) -> i32 {
use std::collections::HashSet;
let s: HashSet<_>= nums.into_iter().collect();
letmut ans =0;
letmut node = head.as_ref();
whilelet Some(n) = node {
if s.contains(&n.val) && (n.next.is_none() ||!s.contains(&n.next.as_ref().unwrap().val)) {
ans +=1;
}
node = n.next.as_ref();
}
ans
}
}