【算法】LeetCode算法题-Remove Element

Visual Studio 2022调试Godot 4 C#项目全攻略:从环境配置到断点调试 本文详细介绍了如何配置Visual Studio 2022以高效调试Godot 4 C#项目。从环境搭建、外部编辑器设置到两种核心调试模式(附加到进程与启动配置)的实战指南,帮助开发者构建无缝的工业级工作流,解决编码乱码、断点失效等常见问题,大幅提升开发与问题排查效率。 阅读详情

这是悦乐书的第150次更新,第152篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第9题(顺位题号是27)。给定整数数组nums和值val,删除nums中所有的val值,元素顺序可以改变,返回删除val值后数组的长度。不能使用新数组接收数据。例如:

给定数组nums = {3,2,2,3}, val = 3
你的函数应返回length = 2
其中nums的前两个元素为2

给定数组nums = [0,1,2,2,3,0,4,2],val = 2
你的函数应该返回length = 5
其中nums的前五个元素包含0,1,3,0和4

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

顺位比较并替换重复值。获取第i个元素,与val比较是否相等,如果相等,则判断val在此是否为连续出现,并使用j来记录索引,直到val不再连续出现的时候,将val第一次出现的值与索引j所代表的值进行互换,依次往后循环。内层嵌套了while循环,但是并不会每次都循环n-1次,其内部也有终止语句。

public int removeElement(int[] nums, int val) {
    if (nums.length == 0) {
        return 0;
    }
    int count = 0;
    int j = 0;
    for (int i=0; i<nums.length;i++) {
        if (nums[i] == val) {
            j = i;
            while (nums[j] == val) {
                j++;
                if(j == nums.length){
                    return count;
                }
            }
            nums[i] = nums[j];
            nums[j] = val;
        }
        count++;
    }
    return count;
}

03 第二种解法

从索引0开始重新设值。定义初始条件count=-1,获取第i位元素与val比较,如果不相等,则nums[++count] = nums[i],此处使用前加加,直接将重复元素用后面的值替换点,而不是像第一种方法那样交换值。如果不习惯看前加加,还有后加加的写法。原则就是count会自然从0往后增加,第i位元素如果等于val,会继续循环,直到不等于,而count处于等待状态,等待非重复元素继续设值。

public int removeElement2(int[] nums , int val) {
    int count = -1; 
    if(nums.length ==1 && nums[0]!=val)
        return 1;

    for ( int n : nums){
        if (n != val && count <= nums.length-2) {
            nums[++count] = n;
        }
    }
    return count+1;
}

// 后加加的写法
public int removeElement3(int[] nums , int val) {
    int count = 0; 
    if(nums.length ==1 && nums[0]!=val){
        return 1;
    }
    for (int i=0; i<nums.length; i++) {
        if (nums[i] != val && count <= nums.length-1) {
            nums[count++] = nums[i];
        }
    }
    return count;
}

04 小结

此题比较简单,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

国科大学习资料--模式识别与机器学习(黄庆明)--2020期末考试题 国科大学习资料–模式识别与机器学习(黄庆明)–2020期末考试题 国科大学习资料–模式识别与机器学习(黄庆明)–2020期末考试题 国科大学习资料–模式识别与机器学习(黄庆明)–2020期末考试题 ============================================================================================================================================================ 阅读详情

相关推荐

陷波滤波器设计以及Simulink仿真

离散型陷波滤波器设计以及simulink仿真

hmq252198885的博客 3166

数据结构之单链表在第i个元素之前插入元素的算法

     数据结构之单链表区第i个元素的算法算法思路:  1.声明一个结点p指向第一个结点,初始化j从1开始  2.当j&lt;i时就遍历链表,让p的指针向后移动,不断指向下一个结点,j累加1  3.若到链表末尾p为空,则说明第i个元素不存在  4.否则查找成功,在系统中生成一个空结点  5.将数据元素e赋给s-&gt;data  6.返回成功     单链表的数据结构:  typedef in...

weixin_34015860的博客 7237

NACA0012的O型网格求解

本篇文章采用偏微分方程数值解法生成NACA0012翼型O型网格,并采用速度势方程求解绕NACA0012翼型迎角为0度时的低速不可压无粘流场。 文章目录一、求解网格1.翼型2.远场3.网格4.迭代5.求解二、求解流场1.偏微分方程2.迭代求解流场三、求解参数1.偏微分方程2.迭代求解四、导出数据 一、求解网格 1.翼型 本次求解网格和流场等采用的是NACA0012(修形)对称翼型,在NACA四位翼型中,第一位数字代表的是弯度,第二位数字代表的是弯度位置,后两位数字代表的是厚度,由于本次翼型的前两位数字都为0,

m0_50746433的博客 6677

【LeetCode】算法题 27 Remove Element

题目:Remove Element Given an array and a value, remove all instances of that value in place and return the new length. Do not allocate extra space for another array, you must do this in place wi

Jojo 295

通义灵码+高德 MCP:40分钟开发出游攻略网站

本文介绍了通义灵码与高德MCP在40分钟内快速开发出游攻略网站的全流程。主要内容包括:1)LingmaIDE开发环境的使用方法,涵盖界面操作、代码编辑、调试和智能编码功能;2)通义灵码智能体与高德MCP2.0的集成步骤,通过输入旅行需求即可自动生成包含天气卡片、景点路线等元素的HTML页面;3)重点展示了如何将行程规划导入高德地图APP,实现导航、打车等出行功能。整个开发过程充分利用了通义灵码的智能编码能力和高德地图的服务接口,显著提升了旅游类应用的开发效率。

soso1968的博客 986

Ubuntu终端AI编程助手配置:Claude Code接入DeepSeek模型全攻略

在软件开发领域,AI编程助手正成为提升开发效率的重要工具。其核心原理是通过大语言模型理解自然语言指令,生成、解释或调试代码。这类工具的技术价值在于将AI能力无缝集成到开发工作流中,减少上下文切换,实现更流畅的人机协作。常见的应用场景包括代码生成、错误调试、代码重构和技术问答等。本文聚焦于在Ubuntu系统中,将流行的终端AI助手Claude Code的后端模型从原版Claude替换为DeepSeek。通过配置环境变量实现API端点和模型的映射,这一过程涉及Node.js环境管理、npm包安装和关键环境变量设

weixin_42527654的博客 378

LeetCode算法题之27. Remove Element(easy)

题目描述: Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input...

DaMoWangZQ的博客 255

kubernetes rook 安装 cephfs

ceph root kubernete osd uuid partuuid

天津托的博客 1543

LeetCode算法题——27. Remove Element

题目: Given an array and a value, remove all instances of that value in place and return the new length. Do not allocate extra space for another array, you must do this in place with constant me

LZTree的专栏 467

07 Zabbix 微信告警

Zabbix 微信告警 1.注册企业微信 企业微信注册地址:https://work.weixin.qq.com 2.进入企业微信后台管理 2.1 添加微信成员 2.2创建应用 2.3 获取四项数据 (1)AgentID (2) Secret (3) 企业ID (4)部门ID 3.Zabbix Server配置 3.1确认脚本目录 # grep alertscripts /etc/zabbix/zabbix_server....

Jian Sun_的博客 1297

【算能】TPU(张量处理单元)的深度解析

算能(SOPHGO)作为国产AI芯片领域的核心企业,其TPU(张量处理单元)以高能效比与全场景覆盖能力为核心竞争力,专注于边缘计算与行业垂直领域的AI推理加速。

浩瀚之水的专栏 1548

python写算法题:leetcode: 27. Remove Element

https://leetcode.com/problems/remove-element/#/description class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :

323

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

leetcode:Remove Element (删除给定元素)【面试算法题】

题目: Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length. 题意把数组中与给定值相同的元素删除,在原数组上修改,返回值是最终元素个数。

Havenoidea 的专栏 1万+

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

LeetCode OJ算法题(二十六):Remove Element

题目: Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new len

op_yu的专栏 448

深度学习工具包 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")

Leetcode 27. Remove Element

https://leetcode.com/problems/remove-element/ class Solution { public: int removeElement(vector<int>& nums, int val) { if(nums.empty()) return 0; int L=nums.size(); ...

weixin_34040079的博客 80

代码随想录算法训练营第一天 | 704. 二分查找、27. 移除元素、35、34

数组基础理论题:704. 二分查找,27. 移除元素 、34、35

weixin_42542290的博客 990

[勇者闯LeetCode] 27. Remove Element

[勇者闯LeetCode] 27. Remove ElementDescription Given an array and a value, remove all instances of that value in place and return the new length. Do not allocate extra space for another array, you mu

fanguzhai的博客 266

[LeetCode] 027. Remove Element (Easy) (C++)

[LeetCode] 027. Remove Element (Easy) (C++)

水果君の日常 2332

leetcode-27. Remove Element

leetcod-27. Remove ElementGiven an array and a value, remove all instances of that value in place and return the new length. Do not allocate extra space for another array, you must do this in place wit

myan991的博客 230

leetcode解题之 27. Remove Element Java版

27. Remove Element Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modify...

he_zhen_的博客 309

Leetcode Remove Element Python 用变量名删除数组中的相同元素,python的优势。

Leetcode 27题 Remove Element Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this ...

润泽的博客 230

leetcode 27

27. Remove Element Given an array and a value, remove all instances of that value in place and return the new length. Do not allocate extra space for another array, you must do this in place wi...

dianpangzhun7106的博客 77

LeetCode | 27. Remove Element贪心算法循环技巧题

Givenan array and a value, remove all instances of that value in-place andreturn the new length. Donot allocate extra space for another array, you must do this by modifying the input array in-place

u012737193的博客 210

容易 删除给定元素

leetcode:Remove Element (删除给定元素)【面试算法题】 分类: leetcode面试算法题2013-10-20 19:13 6838人阅读 评论(0) 收藏 举报 leetcode删除元素Remove Element 题目: Given an array and a value, remove all instances of that va

兔清风的博客 431

27. 移除元素:JavaScript 遍历和双指针两种解法

题目链接LeetCode 27: https://leetcode-cn.com/problems/remove-element/首先我们一起来看题目:方法一解题思路主要思路是遍历数组 ...

LeviDing的博客 468

闯关leetcode——27. Remove Element

leetcode第27题

方亮的专栏 2298
上一篇: 1024程序员节,你屯书了吗?(内含福利)
下一篇: 【算法】LeetCode算法题-Implement strStr
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值