-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathconnectedComponents.java
More file actions
33 lines (32 loc) · 942 Bytes
/
connectedComponents.java
File metadata and controls
33 lines (32 loc) · 942 Bytes
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
import java.util.*;
public class connectedComponents {
public static void main(String[] args){
generateLinkedList obj = new generateLinkedList();
int[] nums = new int[] {5,2,3,0};
int[] eles = new int[] {0,1,2,3,4,5};
ListNode head = obj.generate(eles);
System.out.println(numComponets(head, nums));
}
public static int numComponets(ListNode head, int[] G){
Set<Integer> nums = new HashSet<>();
for(int num : G){
nums.add(num);
}
int res = 0;
boolean prev = false;
ListNode dummy = new ListNode(0);
dummy.next = head;
while(head != null){
if(nums.contains(head.val)){
if(!prev){
res ++;
}
prev = true;
}else{
prev = false;
}
head = head.next;
}
return res;
}
}