https://leetcode-cn.com/problems/linked-list-components/
思路:哈希一下 G G G中出现的值,然后遍历链表判断就行了。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int numComponents(ListNode* head, vector<int>& G) {
if(!head)
return 0;
bool vis[10000]={0};
int siz=G.size();
for(int i=0;i<siz;i++)
vis[G[i]]=1;
int ans=0;
while(head){
while(head&&!vis[head->val])
head=head->next;
if(!head)
break;
++ans;
while(head&&vis[head->val])
head=head->next;
}
return ans;
}
};