当前位置: 首页 > news >正文

leetcode 3217 从链表中移除在数组中存在的节点

一、题目描述

二、解题思路

整体思路

可以采用哈希表(或者集合)+循环模拟的方法来解决这个问题。

具体思路

(1)首先,定义哈希表来标记nums中存在的元素;

 unordered_map<int,bool> hash;

 for(auto x:nums) hash[x]=true;

(2)接着,我们进行循环模拟的准备工作;

<1>为了保证后续节点的一致性,我们引入新头节点newhead;

<2>pre指针用于记录当前处理位置的前一个位置,避免位置丢失,初始化为&newhead;current指针用于指向当前正在处理的位置,初始化为head;

 ListNode newhead(0);

 newhead.next=head;

 ListNode* pre=&newhead;

 ListNode* current=head;

(3)然后,我们通过循环来模拟这个解题过程,当current不为空时进行循环:

<1>如果current指向的值在nums中出现了,即hash.count(current->val)>0,就移除这个节点,并进行指针更新;

<2>如果current指向的值没有在nums中出现,就直接进行指针更新;

while(current!=nullptr){

            //current指向的值在nums中存在

            if(hash.count(current->val)>0){

                pre->next=current->next;

                //delete current;(可以不写,因为链表可能底层实现方式不能delete)

                current=pre->next;

            }

            else{

                pre=current;

                current=current->next;

            }

}

(4)返回处理完的链表。ret用于承接最终的返回结果,即newhead.next;

 ListNode* ret=newhead.next;

 return ret;

注意:相比于ListNode* Newhead=new ListNode(0),直接申请一个ListNode变量可以免去后续的释放环节。

三、代码实现

/*** 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) {//将nums中的元素加入哈希表unordered_map<int,bool> hash;for(auto x:nums) hash[x]=true;//引入虚拟头节点ListNode newhead(0);newhead.next=head;ListNode* pre=&newhead;ListNode* current=head;while(current!=nullptr){//current指向的值在nums中存在if(hash.count(current->val)>0){pre->next=current->next;//delete current;(可以不写,因为链表可能底层实现方式不能delete)current=pre->next;}else{pre=current;current=current->next;}}ListNode* ret=newhead.next;return ret;}
};

http://www.dtcms.com/a/557250.html

相关文章:

  • C++音视频就业路线
  • 46-基于STM32的智能宠物屋设计与实现
  • blender实现手柄控制VR视角
  • 八股训练营第 2 天 | HTTP请求报文和响应报文是怎样的,有哪些常见的字段?HTTP有哪些请求方式?GET请求和POST请求的区别?
  • 【LUT技术专题】SVDLUT: 基于SVD优化的3DLUT
  • 阿里云企业邮箱怎么申请宿迁网站建设SEO优化营销
  • Linux文件搜索完全指南:find、locate和通配符使用详解
  • PyTorch:AI时代的深度学习利器
  • Linux:探究HTTP协议
  • linux实现设备驱动-字符型设备驱动
  • 门户网站排版有引导的网站
  • Linux USB 子系统深度解析
  • Linux time function in C/C++【2】
  • 人工智能学习中深度学习之python基础之迭代器、生成器、文件处理和模块等
  • wordpress显示评论数福建企业seo推广
  • 12.C++:模版进阶
  • 大模型训练评估中的交叉验证详解
  • 变更股东怎样在工商网站做公示做网站的收费标准
  • (142页PPT)立白MES解决方案1Wonderware运营管理平台(附下载方式)
  • 机器学习日报10
  • Linux 2.6.10 调度器负载均衡机制深度解析:从理论到实现
  • 访链家网网站开发嘉定房地产网站建设
  • 多商户商城APP源码开发的未来方向:云原生、电商中台与智能客服
  • Liunx线程安全
  • 基于数据增强与对抗学习的门诊电子病历(EMR)文本分类python编程
  • 企业网站seo推广技巧建设视频网站设计意义
  • VSCode的插件配置同步到gitee
  • 短剧广告联盟 APP 用户画像:基于观看行为的广告精准投放模型
  • 找快照网站查询网站建设博采
  • [论文阅读] AI+ | AI如何重塑审计行业?从“手工筛查”到“智能决策”:AI审计的核心逻辑与未来路径