【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;
    }
};
相关推荐
Pniubi3 小时前
01背包类问题-力扣416.分割等和子集
算法·leetcode·职场和发展
文丑颜不良啊14 小时前
LeetCode3041~3060题目解析
java·leetcode
罗西的思考14 小时前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
文丑颜不良啊15 小时前
LeetCode3101~3120题目解析
java·leetcode
kyle~18 小时前
模型预测控制(MPC)
算法·机器人·控制·传感器
牢姐与蒯20 小时前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好21 小时前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频
电科_银尘21 小时前
【大模型算法与工程 02】线性回归与逻辑回归:从损失函数到决策边界
算法·逻辑回归·线性回归
玄昌盛不会编程1 天前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode
文丑颜不良啊1 天前
LeetCode3061~3080题目解析
java·leetcode