给定链表头结点 head,该链表上的每个结点都有一个 唯一的整型值 。同时给定列表 nums,该列表是上述链表中整型值的一个子集。
返回列表 nums 中组件的个数,这里对组件的定义为:链表中一段最长连续结点的值(该值必须在列表 nums 中)构成的集合
把数组中的元素存入哈希表,然后遍历链表每个节点,找这些节点是否存在于表中。
class Solution {
public:
int numComponents(ListNode* head, vector<int>& nums) {
unordered_set<int> s(nums.begin(), nums.end());//把数组里的元素存入哈希表
int ans = 0;//用于计数
while (head) {//开始遍历
//若表中有节点值,则会返回一个1,没有则返回0
while (head && !s.count(head->val)) head = head->next;
ans += head != nullptr;//计数+1
//链表下个节点也在表中,计数不变
while (head && s.count(head->val)) head = head->next;
}
return ans;
}
};