817. Linked List Components

https://leetcode.com/problems/linked-list-components/description/

/**
 * 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> s;
        for (auto i : G)
            s.insert(i);
        int res = 0;
        bool connected = false;
        while (head) {
            if (s.find(head->val) == s.end()) {
                connected = false;
            }
            else {
                if (!connected) {
                    res++;
                    connected = true;
                }
            }
            head = head->next;
        }
        return res;
    }
};

 

posted @ 2018-11-19 00:07  JTechRoad  阅读(76)  评论(0编辑  收藏  举报