Day25: [LeetCode中等] 817. 鏈表組件

Day25: [LeetCode中等] 817. 鏈表組件

題源:

來自leetcode題庫:

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

思路:

就是先把vector裏的整數都放在set裏,然後遍歷鏈表,一旦有組件中的值,就計數加一,然後把組件鄰近值越過。

代碼:

dirty code湊合看吧

/**
 * 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;
        unordered_set<int> se;
        for(auto i:G){
            se.insert(i);
        }
        int res=0;
        while(head){
            if(se.find(head->val)!=se.end()){
                head=head->next;
                while(head){
                    if(se.find(head->val)==se.end()) break;
                    head=head->next;
                }
                res++;
            }
            if(head) head=head->next;
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章