【set】个人练习-Leetcode-817. Linked List Components

题目链接:https://leetcode.cn/problems/linked-list-components/description/

题目大意:给出一个vector<int> nums,其中有一些数字。再给出一个链表的头指针head,链表内的元素各不相同。如果链表中有某一段(长度大于等于1)的元素都在nums中出现过,那么就算一个component,求链表中的component的个数。

思路:【判断是否在nums中出现过】直接用set就好了,如果是STL的话,用count方法很方便。不过测试了一下后发现时间花得有点多,于是换成了数组。

使用两个布尔值:last表示【上一个元素】【是否在nums中出现过】,用flag表示【当前元素】【是否在nums中出现过】

  • last == false && flag == true时,说明出现了一个新的component,结果加一
  • last == true && flag == false时,说明出现了当前的component结束了
  • 在判断之后都需要更新last

完整代码

cpp 复制代码
class Solution {
public:
    int numComponents(ListNode* head, vector<int>& nums) {
        bool nm[10001] = {0};
        for (auto x : nums) {
            nm[x] = true;
        }

        ListNode* ptr = head;
        bool last = false;
        int ret = 0;
        
        while (ptr) {
            bool flag = nm[ptr->val];

            if (flag != last) {
                if (last) {
                    last = false;
                }
                else {
                    ret++;
                    last = true;
                }
            }
            ptr = ptr->next;
        }

        return ret;
    }
};
相关推荐
周末也要写八哥3 小时前
经典算法实例:游戏中弱角色的数量(二)
算法
是Yu欸3 小时前
鸿蒙PC移植:2048 从网页小游戏到 AI 桌面应用
大数据·人工智能·算法·数据挖掘·openharmony·codex
鹿角片ljp3 小时前
KV Cache 解析
java·算法
liliangcsdn4 小时前
IVOL与偏度因子的对比测量分析
算法
threerocks5 小时前
Jev 入门第一课
算法
西柚研究生1234566 小时前
论文分析17:YOLOv11_UAVNet:无人机航拍图像专用目标检测算法
人工智能·python·深度学习·算法·目标检测
hetao17338376 小时前
2026-09-17 hetao1733837 的刷题记录
c++·算法
午彦琳7 小时前
2026.9.17
数据结构·算法·leetcode
木井巳8 小时前
【记忆化搜索】不同路径
java·算法·leetcode·深度优先·剪枝·推荐算法
怕浪猫9 小时前
从 Windows 换到 Mac 三个月,我真香了
算法·面试·架构