public static int numComponents(ListNode head, int[] nums) {
HashSet<Integer> set = new HashSet<>(); for (int num : nums) { set.add(num); } ListNode p = head; int count =0; while (p != null){ if(set.contains(p.val) && (p.next == null || !set.contains(p.next.val))) count++; p = p.next; } return count; }
public static void main(String[] args) {
ListNode head = new ListNode(); ListNode nextNode; nextNode=head; int[] nodes = {0,1,2};
for(int i=0;i<nodes.length;i++){ ListNode node = new ListNode(nodes[i]); nextNode.next=node; nextNode=nextNode.next; } int[] nums = {0,2}; int i = numComponents(head, nums); System.out.println(i); }