817. Linked List Components

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public int numComponents(ListNode head, int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}

int count = 0;

ListNode curr = head;
while (curr != null) {
if (set.contains(curr.val)) {
while (curr.next != null && set.contains(curr.next.val)) {
curr = curr.next;
}

// now: curr.next == null or set.notContains(curr.next.val)
count++;
}
curr = curr.next;
}

return count;
}
}

References

817. Linked List Components