【实战】ACM 选手图解 LeetCode 移除元素

LeetCode 27.移除元素。 给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。 给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。 不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。 元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/remove-element 示例 1: 输入:nums = [3,2,2,3], val = 3 输出:2, nums = [2,2] 解释:函 阅读详情

大家好,我是帅蛋~

因为数组实在太常用了,我就挑几种类型的题来讲一下,大致是图中读者说的那几个。

以后想起来别的再继续补充。

今天解决移除元素,是快慢指针的经典题目。话不多说,直接开整。

10c1045ba37361eaa7aed40a7b96568

LeetCode 27:移除元素

题意

给你一个数组 nums 和一个 val,原地移除所有数值等于 val 的值,并返回移除后数组的新长度。

示例

输入:nums = [0,1,2,2,3,0,4,2], val = 2

输出:5, nums = [0,1,4,0,3]

解释:函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。注意这五个元素可为任意顺序。你不需要考虑数组中超出新长度后面的元素。

提示

必须使用 O(1) 空间复杂度并原地修改输入数组。

  • 0 <= len(nums) <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100

题目解析

水题,题目简单。

这道题相当于数组元素的删除,既然涉及到数组的删除,就不是想当然的删除。

我在文章【ACM 选手带你玩转数组】中讲过:

数组是用连续的一段内存空间,来存储相同数据类型数据的集合。因为这个“连续内存存储”,使得数组在插入或者删除的元素的时候,其它元素也要相应的移动。

这道题数组的数据量很小,最多只到 100 个,所以可以用暴力手法破解。

所谓暴力手法就是最无脑的方式,两层 for 循环,第一层 for 循环从 0 开始遍历数组,第二层 for 循环维护后面的元素向前移动。

比如第一层 for 循环遍历到下标为 2 的位置发现 nums[2] == val,那么第二层循环就将 i+1 ~ n -1 位置上的元素全部向前移动一个位置。

因为是双重 for 循环,此时的时间复杂度为 O(n²)。

虽然也能 AC,但显然作为新时代的三好男人,本帅蛋在这方面追求的肯定不是慢,而是秒男的极致,我要快!

531419fc699416d94ae936e8eec5a28

要我快点的话,这就不得不提快慢指针了。

【实战】ACM 选手图解 LeetCode 删除字符串中的所有相邻重复项 图解 LeetCode 1047:删除字符串中的所有相邻重复项 阅读详情

相关推荐

【实战】ACM 选手图解 LeetCode 用栈实现队列

图解 LeetCode 232:用栈实现队列

用有趣有味的方式,学习有价值的编程知识。 504

【实战】ACM 选手图解 LeetCode 有序数组的平方

图解 LeetCode 977:有序数组的平方。

用有趣有味的方式,学习有价值的编程知识。 559

我对ACM初学者想说的话

1 算法学习 ACM算法的学习,一般看刘汝佳的系列书籍即可。初学者需要看的书是《算法竞赛入门经典》(俗称小白书),或者可以看《算法竞赛入门经典(第二版)》(俗称紫书)。理论上说,紫书的质量比小白书高得多,小白书介绍的内容紫书都有讲,紫书还增加了介绍C++语法的一个章节。但是紫书的题目相当灵活,对初学者来说未必简单(不要因为我这么说就以为小白书的题就容易了),大家可以都先看一看,最...

代号4101的专栏 1万+

一生一芯预学习:从零搭建Verilator仿真环境与NVBoard实战

本文详细介绍了如何从零搭建Verilator仿真环境,并完成NVBoard实战项目,为'一生一芯'预学习提供完整指导。内容包括环境配置、工具安装、波形生成、自动化构建及可视化调试技巧,帮助初学者快速掌握数字逻辑设计与仿真验证的核心技能。

keras9composer的博客 701

(一)PyBullet机器人仿真入门:从环境搭建到实例解析

本文详细介绍了PyBullet机器人仿真平台从零开始的完整入门指南。内容涵盖环境搭建、官方示例解析、核心操作(连接、世界与模型)、关节控制与状态读取,以及碰撞检测、传感器模拟等高级功能,帮助读者快速掌握这一强大的机器人仿真工具。

weixin_29062865的博客 1383

【免费】最新区块链钱包和私钥的助记词碰撞器,bybit使用python开发

【免费】最新助记词钱包碰撞器,全链全网络,一周左右就有,稳定高效。

weixin_48529185的博客 1万+

【Godot4自学手册】第一节配置Godot运行环境

Godot是一款自由开源、由社区驱动的 2D 和 3D 游戏引擎!它是一款功能丰富的跨平台游戏引擎,可以通过统一的界面创建 2D 和 3D 游戏。它提供了一套全面的通用工具,因此用户可以专注于制作游戏,而无需重新发明轮子。游戏可以一键导出到多个平台,包括主流的桌面平台(Linux、macOS、Windows)、移动平台(Android、iOS)、基于 Web 的平台以及主机平台。

zhaoyang314的博客 5986

S32K3双核实战:手把手教你用EB配置CAN与CANFD(附中断/轮询代码对比)

本文详细解析了NXP S32K3双核处理器在CAN/CANFD通信开发中的实战应用。通过Elektrobit配置工具链,从双核通信架构设计到EB tresos Studio配置全流程,再到中断与轮询模式的代码实现对比,全面指导开发者优化S32K3 FlexCAN模块性能,提升汽车电子系统的通信效率与可靠性。

weixin_30955617的博客 440

SAP HANA 中的 Union Node Pruning:让 Calculation View 少走弯路的关键优化

摘要:SAP HANA的Union Node Pruning技术通过在执行前排除无关数据源来优化查询性能。该技术主要采用三种方式:Constant Mapping(适用于规则稳定的场景)、Pruning Configuration Table(灵活性高)和Column-Based Pruning(基于列可用性)。典型应用场景包括分层存储的数据查询,如区分当前和历史销售数据。需要注意的是,当查询发生Unfolding且不含聚合时,Pruning可能失效,此时可通过NO_CALC_VIEW_UNFOLDING提

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 875

IP-Guard分类管理详解

大家都知道在配置IPGUARD策略前需要做分类库进行设置和分类。 1、应用程序:可以分类,例如上班时间只能用OFFICE和WPS,记事本等办公软件,可以在分类里设置一个类 ;办公软件,在未分类里找到OFFICE,WPS等拖入心建的分类里就可以在配置策略里调用。 2、网站分类也不一样,可以按照自己方式自定义。也可以导入厂家已经收集到的网站分类。 3、邮箱分类:可以提前定义好一个或...

IP-Guard专栏 591

CREO图文教程:三维设计案例之矿泉水瓶实例图文教程之详细攻略

草绘,先绘制中心线,绘制底部宽度;对称标注:点击左端点,中心线,左端点,中键即可标注;给定高度;样条曲线绘制外形(双击样条曲线,点击下栏的控制模式(第一个按钮),再拉动控制样条曲线上的各个点)打勾即可得到三维实体。......

走向CTO之路 1935

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

上一篇: 【图解】ACM 选手带你玩转数组。
下一篇: 【实战】ACM 选手图解 LeetCode 有序数组的平方
编程文青李狗蛋
博客等级 码龄5年 27粉丝 27原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值