【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;
    }
};
相关推荐
Tim_1014 小时前
【LeetCode】338、比特位计数
c++·算法·leetcode
木子算法14 小时前
不是重心也不是中点:费马—韦伯点、它的最优性条件与迭代求解
人工智能·算法·目标跟踪
2401_8322981015 小时前
人机协同:AI时代全新工作与学习范式
职场和发展
童园管理札记15 小时前
从政策驱动到课堂落地:2026年“人工智能+教育”全景解读与技术实践指南
人工智能·python·深度学习·职场和发展·学习方法
tryxr15 小时前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_315 小时前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Selvaggia15 小时前
DMD(Distribution Matching Distillation,分布匹配蒸馏)
算法
Navigator_Z16 小时前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.16 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
开开心心就好16 小时前
安卓手写文字生成工具,多种纸张一直免费
网络·网络协议·tcp/ip·leetcode·智能手机·电脑·模拟退火算法