LeetCode每日一题- day18

LeetCode每日一题- day18

新手入坑LeetCode,每天打卡一道题
算法不一定很好,只是我自己的一个水平体现,做个自己刷题的记录,欢迎交流学习
(尽量AC LeetCode官方的每日一题)
欢迎交流学习!

题目:817. 链表组件

给定链表头结点 head,该链表上的每个结点都有一个 唯一的整型值 。同时给定列表 nums,该列表是上述链表中整型值的一个子集。
返回列表 nums 中组件的个数,这里对组件的定义为:链表中一段最长连续结点的值(该值必须在列表 nums 中)构成的集合。

思路:

读懂题即可

代码:

class Solution {
public:
    int numComponents(ListNode* head, vector<int>& nums) {
        unordered_set<int> s(nums.begin(), nums.end());
        int ans = 0;
        while (head) {
            while (head && !s.count(head->val)) head = head->next;
            ans += head != nullptr;
            while (head && s.count(head->val)) head = head->next;
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/Nmj_World/article/details/127292698