-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy path0817-linked-list-components.js
44 lines (41 loc) · 1.05 KB
/
0817-linked-list-components.js
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 817. Linked List Components
* https://leetcode.com/problems/linked-list-components/
* Difficulty: Medium
*
* You are given the head of a linked list containing unique integer values and an integer array
* nums that is a subset of the linked list values.
*
* Return the number of connected components in nums where two values are connected if they appear
* consecutively in the linked list.
*/
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number[]} nums
* @return {number}
*/
var numComponents = function(head, nums) {
const numSet = new Set(nums);
let componentCount = 0;
let inComponent = false;
let current = head;
while (current) {
if (numSet.has(current.val)) {
if (!inComponent) {
componentCount++;
inComponent = true;
}
} else {
inComponent = false;
}
current = current.next;
}
return componentCount;
};