Skip to content

Commit 846e333

Browse files
committed
update cheatsheet/linked_list.md
1 parent cb02115 commit 846e333

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

doc/cheatsheet/linked_list.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1382,4 +1382,40 @@ while (current != null) {
13821382

13831383
return prev;
13841384
}
1385+
```
1386+
1387+
### 2-11) Linked List Components
1388+
1389+
```java
1390+
// java
1391+
// LC 817
1392+
// V1
1393+
// IDEA: set, linkedlist (gpt)
1394+
public int numComponents_1(ListNode head, int[] nums) {
1395+
// Convert nums array to a HashSet for O(1) lookups
1396+
Set<Integer> numsSet = new HashSet<>();
1397+
for (int num : nums) {
1398+
numsSet.add(num);
1399+
}
1400+
1401+
int count = 0;
1402+
boolean inComponent = false;
1403+
1404+
// Traverse the linked list
1405+
while (head != null) {
1406+
if (numsSet.contains(head.val)) {
1407+
// Start a new component if not already in one
1408+
if (!inComponent) {
1409+
count++;
1410+
inComponent = true;
1411+
}
1412+
} else {
1413+
// End the current component
1414+
inComponent = false;
1415+
}
1416+
head = head.next;
1417+
}
1418+
1419+
return count;
1420+
}
13851421
```

0 commit comments

Comments
 (0)