Skip to content

Commit 95efabf

Browse files
committed
Add solution #817
1 parent 1911548 commit 95efabf

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,7 @@
625625
814|[Binary Tree Pruning](./0814-binary-tree-pruning.js)|Medium|
626626
815|[Bus Routes](./0815-bus-routes.js)|Hard|
627627
816|[Ambiguous Coordinates](./0816-ambiguous-coordinates.js)|Medium|
628+
817|[Linked List Components](./0817-linked-list-components.js)|Medium|
628629
819|[Most Common Word](./0819-most-common-word.js)|Easy|
629630
821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy|
630631
824|[Goat Latin](./0824-goat-latin.js)|Easy|

Diff for: solutions/0817-linked-list-components.js

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* 817. Linked List Components
3+
* https://leetcode.com/problems/linked-list-components/
4+
* Difficulty: Medium
5+
*
6+
* You are given the head of a linked list containing unique integer values and an integer array
7+
* nums that is a subset of the linked list values.
8+
*
9+
* Return the number of connected components in nums where two values are connected if they appear
10+
* consecutively in the linked list.
11+
*/
12+
13+
/**
14+
* Definition for singly-linked list.
15+
* function ListNode(val, next) {
16+
* this.val = (val===undefined ? 0 : val)
17+
* this.next = (next===undefined ? null : next)
18+
* }
19+
*/
20+
/**
21+
* @param {ListNode} head
22+
* @param {number[]} nums
23+
* @return {number}
24+
*/
25+
var numComponents = function(head, nums) {
26+
const numSet = new Set(nums);
27+
let componentCount = 0;
28+
let inComponent = false;
29+
30+
let current = head;
31+
while (current) {
32+
if (numSet.has(current.val)) {
33+
if (!inComponent) {
34+
componentCount++;
35+
inComponent = true;
36+
}
37+
} else {
38+
inComponent = false;
39+
}
40+
current = current.next;
41+
}
42+
43+
return componentCount;
44+
};

0 commit comments

Comments
 (0)