您的位置:首页 > 财经 > 金融 > Leetcode3217. 从链表中移除在数组中存在的节点

Leetcode3217. 从链表中移除在数组中存在的节点

2025/2/22 16:55:00 来源:https://blog.csdn.net/ProgramNovice/article/details/140649175  浏览:    关键词:Leetcode3217. 从链表中移除在数组中存在的节点

Every day a Leetcode

题目来源:3217. 从链表中移除在数组中存在的节点

解法1:集合 + 链表遍历

代码:

/** @lc app=leetcode.cn id=3217 lang=cpp** [3217] 从链表中移除在数组中存在的节点*/// @lc code=start
/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode() : val(0), next(nullptr) {}*     ListNode(int x) : val(x), next(nullptr) {}*     ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution
{
public:ListNode *modifiedList(vector<int> &nums, ListNode *head){unordered_set<int> dict(nums.begin(), nums.end());ListNode *dummy = new ListNode();dummy->next = head;ListNode *p = dummy;while (p->next){if (dict.contains(p->next->val))p->next = p->next->next;elsep = p->next;}return dummy->next;}
};
// @lc code=end

结果:

在这里插入图片描述

复杂度分析:

时间复杂度:O(n+m),其中 n 是数组 nums 的长度,m 是链表的长度。

空间复杂度:O(n),其中 n 是数组 nums 的长度。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com