# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = NoneclassSolution(object):defnumComponents(self, head, G):""" :type head: ListNode :type G: List[int] :rtype: int """ Gset = set(G) cur = head ans = 0while cur:if cur.val in Gset and (cur.next isNoneor cur.next.val notin Gset): ans += 1 cur = cur.nextreturn ans
Java
classSolution{publicintnumComponents(ListNode head, int[] G){ Set<Integer> Gset = new HashSet();for (int x: G) Gset.add(x); ListNode cur = head;int ans = 0;while (cur != null) {if (Gset.contains(cur.val) && (cur.next == null || !Gset.contains(cur.next.val))) ans++; cur = cur.next; }return ans; }}