leetcode刷题26 删除排序数组中的重复项 Remove Duplicates from Sorted Array(简单) Python Java

【信息科学与工程学】【数据科学】数据科学领域 第六篇 算法设计 07 堆、栈、表、矩阵、集合、队列、数组、字符串、树、图、动态规划、结构体、元组的算法01 当前段必须包含所有字符的最后出现位置。1. 字符串分割成最多片段2. 基因序列功能域划分3. 文本段落划分4. 音频声道分离5. 图像色彩分区6. 社交网络社群划分7. 蛋白质结构域8. 音乐乐章分段9. 代码模块划分10. 章节划分特征:一次扫描,贪心确定边界。 阅读详情

题目:

给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。

不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。

示例 1:

给定数组 nums = [1,1,2],

函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。

你不需要考虑数组中超出新长度后面的元素。


示例 2:

给定 nums = [0,0,1,1,1,2,2,3,3,4],

函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。

你不需要考虑数组中超出新长度后面的元素。


说明:

为什么返回数值是整数,但输出的答案是数组呢?

请注意,输入数组是以“引用”方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。

解法一:

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:  # 判断是否为空数组
            return 0

        start = 0  # 新数组下标
        for i in range(1, len(nums)):
            if nums[i] != nums[start]:
                start += 1
                nums[start] = nums[i]
        return start + 1

if __name__ == '__main__':
    a = Solution()
    result = a.removeDuplicates([1,2,2,3,3,3,4])
    print(result)

结果为4

 

解法二:

class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        pe: int
        """
        i=0
        while i<len(nums)-1:
            if nums[i]==nums[i+1]:  # 如果元素相同则从数组中移除
                nums.remove(nums[i])
            else:
                i=i+1  # 元素不同则数组下标加一
        return len(nums)

if __name__ == '__main__':
    a = Solution()
    result = a.removeDuplicates([1,2,2,3,3,3,4])
    print(result)

 

以下是Java版本:

/**
 * 移除有序数组中的重复元素:
 *    给定一个排序的数组,将数组中的重复元素去掉,相同的只保留一个,并且返回数组新的元素个数,
 *    不要创建一个新的数组来保存结果。
 *    
 * 做法是维护两个指针,一个保留当前有效元素的长度,一个从前往后扫,然后跳过那些重复的元素。
 * 因为数组是有序的,所以重复元素一定相邻,不需要额外记录。
 * 时间复杂度是O(n),空间复杂度O(1)。
*/
public class RemoveDuplicates {
	 public int removeDuplicates(int[] nums) {
	        if(nums == null || nums.length==0)  
	        return 0;  
	    int index = 1;  
	    for(int i=1;i<nums.length;i++) {  
	        if(nums[i]!=nums[i-1]){  
	            nums[index]=nums[i];  
	            index++;  
	        }  
	    }  
	    return index;  
       }
}

 

Leetcode 26. Remove Duplicates from Sorted Array--从有序数组中删除重复元素;从有序数组中找出不重复元素放到数组左边,返回不重复元素的个数 Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifyi... 阅读详情

相关推荐

佳能C3025打印机扫描方法

佳能C3025彩色打印机扫描方法 步骤一、如果打印机处于休眠状态,可按图中标记的按钮唤醒打印机; 然后点击屏幕上的【扫描】 步骤二、扫描类型选择【文件】 步骤三、点击屏幕上的【地址簿】 步骤四、此时屏幕胡看到名字,如果看不到自己的名字,可往下滑动直到看到自己的名字,然后点击自己的名字,再点击右下角的【应用】 步骤五、点击【发送设置】,可看到文件格式为PDF,点击可以选择JPEG的图片格式。...

weixin_46019317的博客 2万+

26. Remove Duplicates from Sorted Array

26. 删除排序数组中的重复项 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 示例1: 给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 你不需要考虑数组中超出新长度...

GGGGITFKBJG的主页 154

基于MS5351的三通道可编程时钟发生器设计

时钟发生器是数字系统时序验证与信号完整性测试的核心基础设备,其原理基于锁相环(PLL)对参考晶振进行倍频与分频控制,通过寄存器配置实现多路独立频率输出。技术价值体现在高精度、低抖动、快速切换与工程可部署性之间取得平衡,尤其适用于FPGA/ASIC参考时钟调试、ADC/DAC采样时钟验证及嵌入式硬件时序裕量评估等场景。本方案采用MS5351三通道时钟芯片与ESP32主控协同架构,在保证LVCMOS输出质量与I²C可编程性的前提下,优化电源噪声抑制、晶体负载匹配和跨板信号完整性,兼顾成本、周期与实测稳定性,为实

weixin_31715353的博客 214

26. Remove Duplicates from Sorted Array题目和答案详解

1 题目简述 Given a sortedarray, remove the duplicates in-place such that each element appear only onceand return the new length. 给定一个排序数组,删除重复的位置,使每个元素只出现一次,并返回新的长度。 Do not allocateextra space for an

Disappear_XueChao的博客 735

九齐NY8B062F单片机:12位ADC与4路PWM在智能家居控制中的实战应用

本文详细介绍了九齐NY8B062F单片机在智能家居控制中的实战应用,重点解析其12位ADC高精度传感器数据采集和4路PWM精准驱动技术。通过实际案例展示如何利用该单片机实现温湿度监测、灯光调节及电机控制,并分享低功耗设计与抗干扰方案,为低成本高可靠性的智能家居设备开发提供完整解决方案。

rnn9storyteller的博客 733

微信公众平台 - 微信内置浏览器 WeixinJSBridge.invoke(‘xxx‘) API 报错:system:access_denied(常见于微信支付、分享朋友圈/转发好友等功能)解决方案

微信支付提示System:access_denied,调用微信支付返回:system:access_denied为什么,安卓版微信支付偶尔出现system:access_denied,微信公众号开发分享出现system:access_denied,system:access_denied如何解决?微信WeixinJSBridge.invoke(‘xxx‘)API调用后出现报错,微信内部H5WeixinJSBridge.invokesystem:access_denied,使用微信jssdk时报ac

🏆 前端领域优质创作者 5147

闯关leetcode——26. Remove Duplicates from Sorted Array

leetcode第26题

方亮的专栏 1225

点云目标检测:open3d多窗口联动可视化

多个模型之间的对比除了指标之外,还需要可以直接直观的对比可视化结果,这次介绍一下如何使用open3d同时打开两个窗口分别加载两个模型的结果进行对比,同时实现两个窗口的联动,也就是当一个窗口拖动或者缩放时另外一个窗口也跟着做同样的变换。

zhaoguanhua的博客 4688

​LeetCode 26:删除排序数组中的重复项 Remove Duplicates from Sorted Array

给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 Given a sorted array nums, remove the duplicates in-place such that each element appear only once and re...

爱写Bug 213

振镜控制卡硬件接口揭秘:XY2-100/SL2-100协议对比

本文对比分析了工业振镜控制领域两种主流数字通信协议XY2-100和SL2-100的硬件接口差异与应用场景。XY2-100作为开放式协议兼容性强,采用LVDS差分信号传输,适用于激光打标等中高精度场景;SL2-100为半封闭协议,采用RS485差分信号,专为高速响应场景设计。文章详细解析了两种协议的引脚定义、通信机制和性能参数,指出XY2-100适配多品牌振镜且调试简单,SL2-100则更适合Nutfield专用设备的高速高精度需求。最后提供了接口调试的实操建议和选型逻辑,强调应根据具体应用场景的精度、速度和

远程部署调试 运行安装 项目调试 二次开发 项目技术新 持续迭代 部分源码免费分享 653

【2026最新版】PCL点云处理算法汇总(C++长期更新版)

PCL学习目录。博客长期更新,最近一次更新时间为:2026年10月4日。

点云侠的博客 63万+

LeetCode 26 — Remove Duplicates from Sorted Array(C++ Java Python)

题目:http://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/ Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

龙之梦 5496

【异常】OpenClaw提示异常 1302:您的账户已达到速率限制,请您控制请求频率

摘要:系统返回1302错误码提示"账户已达到速率限制",表明请求频率超过服务阈值。主要原因是并发请求数达上限或请求过于密集。解决方案包括:降低并发请求量、引入请求队列机制平滑流量,或根据服务规则提升账户权益等级以获取更高并发额度。建议优先优化请求频率控制策略,避免触发系统限流机制。

奶爸的编程之路,也就一周冷个三天 1151

26. 删除排序数组中的重复项 Remove Duplicates from Sorted Array

文章目录题目:删除排序数组中的重复项 Remove Duplicates from Sorted Array参考答案遇到的问题 题目:删除排序数组中的重复项 Remove Duplicates from Sorted Array 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额...

DataScience成长之路 247

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

80. Remove Duplicates from Sorted Array II

80. Remove Duplicates from Sorted Array IIclass Solution { public: int removeDuplicates(vector&lt;int&gt;&amp; nums) { if(nums.size()&lt;3) return nums.size(); int firs...

小菜鸟的博客 457

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

【leetcode刷题】[简单]26. 删除排序数组中的重复项(remove duplicates from sorted array)-java

删除排序数组中的重复项 remove duplicates from sorted array题目分析解答 题目 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 示例 1: 给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组...

mikuluna的博客 255

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

leet_26_Remove_Duplicates_from_Sorted_Array

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.Do not allocate extra space for another array, you must do this by modifying...

wonengguwozai的博客 361

[LeetCode] Remove Duplicates from Sorted Array 从有序数组中删除重复项

给定一个有序数组,你需要原地删除其中的重复内容,使每个元素只出现一次,并返回新的长度。 不要另外定义一个数组,您必须通过用 O(1) 额外内存原地修改输入的数组来做到这一点。 示例: 给定数组: nums = [1,1,2], 你的函数应该返回新长度 2, 并且原数组nums的前两个元素必须是1和2 不需要理会新的数组长度后面的元素 思路:用快慢指针来记录遍历的坐标,最开始时两个指针都...

可以叫我啪叽的石头 1941

【LeetCode】26. Remove Duplicates from Sorted Array - Java实现

文章目录1. 题目描述:2. 思路分析:3. Java代码: 1. 题目描述: Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for ano...

小怪孩的成长之路 634
上一篇: leetcode刷题21 合并两个有序链表 Merge Two Sorted Lists(简单) Python Java
下一篇: leetcode刷题53 最大子序和 Maximum Subarray(简单) Python Java
SpringRolls
博客等级 码龄9年 73粉丝 129原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值