-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
41 lines (36 loc) · 924 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
39
40
41
/**
* 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) {
// this solution use O(n) time and O(n) space
int length = 0;
ListNode p = head;
while (p != null) {
p = p.next;
length++;
}
int[] buckets = new int[length];
for (int val : G)
buckets[val] = 1;
int count = 0;
boolean flag = false;
while (head != null) {
if (buckets[head.val] == 1) {
if (!flag) {
count++;
flag = true;
}
} else {
flag = false;
}
head = head.next;
}
return count;
}
}