817. Linked List Components
class Solution {
public:
int numComponents(ListNode* head, vector<int>& nums) {
// 将 nums 存储到一个 unordered_set 中,方便 O(1) 查找
unordered_set<int> numSet(nums.begin(), nums.end());
int count = 0;
bool inComponent = false; // 标记当前是否处于一个组件中
while (head) {
if (numSet.count(head->val)) {
// 当前节点在 nums 中
if (!inComponent) {
// 这表示我们找到了一个新的组件
count++;
inComponent = true;
}
} else {
// 当前节点不在 nums 中
inComponent = false;
}
head = head->next; // 移动到下一个节点
}
return count;
}
};