LeetCode 817:链表组件(计数)

解法一:常规解法,建图+DFS,时间复杂度O(n)+O(n),空间复杂度因为需要存储图,所以是O(n)

这种方法是通解,对于所有图都适用。

/**
 * 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> f(G.begin(), G.end());
        unordered_map<int, vector<int>> g;
        //根据G中节点,从list中建立图g
        int u = head->val;
        while(head->next) {
            head = head->next;
            int v = head->val;
            if(f.count(v) && f.count(u)) {
                g[u].push_back(v);
                g[v].push_back(u);
            }
            u = v;
        }
        //DFS
        int ans = 0;
        unordered_set<int> visited;
        for(int u : G) {
            if(visited.count(u)) continue;
            ++ans;
            dfs(u, g, visited);
        }
        return ans;

    }
private:
    void dfs(int cur, unordered_map<int, vector<int>>& g, unordered_set<int>& visited) {
        if(visited.count(cur)) return; //当前节点在visited集合中计数不为0(为1),说明已经遍历过该节点
        visited.insert(cur);
        for(int next : g[cur]) { //int next 与 const int next均可以通过,为什么要加const?
            dfs(next, g, visited);
        }
    }
};

解法二:利用list的特性,将G中的点映射到list上的话,每一个组件内部都是线性连接的,外部应该是断开的,所以可以利用这种特性,遍历链表,当一个节点在G中,但它的下一个节点为null或者下一节点的值不在G中,则说明这是一个组建的末尾元素,ans++,再继续遍历

class Solution {
public:
    int numComponents(ListNode* head, vector<int>& G) {
        unordered_set<int> g(G.begin(), G.end());
        int ans = 0;
        while(head) {
            if(g.count(head->val) && (!head->next || !g.count(head->next->val)))
                ++ans;
            head = head->next;
        }
        return ans;
    }
};
发布了97 篇原创文章 · 获赞 11 · 访问量 2495

猜你喜欢

转载自blog.csdn.net/chengda321/article/details/102505074