forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
38 lines (37 loc) · 893 Bytes
/
Solution.java
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int numComponents(ListNode head, int[] G) {
if (head == null || G == null) {
return 0;
}
Set<Integer> set = new HashSet<>();
for (int val : G) {
set.add(val);
}
int n = G.length;
ListNode cur = head;
int cnt = 0;
boolean flag = false;
while (cur != null) {
while (cur != null && set.contains(cur.val)) {
flag = true;
cur = cur.next;
}
if (flag) {
++cnt;
flag = false;
}
if (cur != null) {
cur = cur.next;
}
}
return cnt;
}
}