-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0817.cpp
55 lines (51 loc) · 1.13 KB
/
0817.cpp
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
45
46
47
48
49
50
51
52
53
54
55
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int numComponents(ListNode *head, vector<int> &G) {
// return func1(head, G);
return func2(head, G);
}
// ** straight forward, need O(N) extra space
int func1(ListNode *head, vector<int> &G) {
unordered_set<int> set;
for (int g : G) {
set.insert(g);
}
bool linking = false;
int res = 0;
while (head != NULL) {
if (set.count(head->val) <= 0) {
linking = false;
} else {
if (linking) {
// ** nothing
} else {
linking = true;
res++;
}
}
head = head->next;
}
return res;
}
// ** referance, more concise
int func2(ListNode *head, vector<int> &G) {
unordered_set<int> setG(G.begin(), G.end());
int res = 0;
while (head != NULL) {
if (setG.count(head->val) &&
(head->next == NULL || setG.count(head->next->val) <= 0)) {
res++;
}
head = head->next;
}
return res;
}
};