817. Linked List Components
You are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values.
Return the number of connected components in nums where two values are connected if they appear consecutively in the linked list.
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
|
class Solution { public: int numComponents(ListNode* head, vector<int>& nums) { unordered_set<int> n(nums.begin(), nums.end()); int res = 0; bool consequtive = false; while(head) { if(!n.count(head->val)) { if(consequtive) res++; consequtive = false; } else consequtive = true; head = head->next; } return res + consequtive; } };
|