[leetcode]817. Linked List Components
Analysis
ummmmm~—— [ummmm]
We are given head, the head node of a linked list containing unique integer values.
We are also given the list G, a subset of the values in the linked list.
Return the number of connected components in G, where two values are connected if they appear consecutively in the linked list.
其实就是计算图的连通分量,然后并没有给出邻接表,而是给了一个链表
Implement
/**
* 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) {
unordered_set<int> graph(G.begin(), G.end());
int res = 0;
while(head){
bool flag = false;
while(head && graph.count(head->val)){
head = head->next;
flag = true;
}
if(flag)
res++;
if(head)
head = head->next;
}
return res;
}
};