817. Linked List Components ¶ Time: $O(n)$ Space: $O(n)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14class Solution { public: int numComponents(ListNode* head, vector<int>& nums) { int ans = 0; unordered_set<int> setNums{nums.begin(), nums.end()}; for (; head; head = head->next) if (setNums.count(head->val) && (!head->next || !setNums.count(head->next->val))) ++ans; return ans; } }; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15class Solution { public int numComponents(ListNode head, int[] nums) { int ans = 0; Set<Integer> setNums = new HashSet<>(); for (final int g : nums) setNums.add(g); for (; head != null; head = head.next) if (setNums.contains(head.val) && (head.next == null || !setNums.contains(head.next.val))) ++ans; return ans; } } 1 2 3 4 5 6 7 8 9 10 11class Solution: def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int: ans = 0 numsSet = set(nums) while head: if head.val in numsSet and (head.next == None or head.next.val not in numsSet): ans += 1 head = head.next return ans