leetcode 287.Find the Duplicate Number(找重复数字)

[Leetcode]287. Find the Duplicate Number简单解法及解释 双指针复杂度O(n) 题目链接:Find the Duplicate Number Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there 阅读详情

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Example 1:

Input: [1,3,4,2,2]
Output: 2
Example 2:

Input: [3,1,3,4,2]
Output: 3
Note:

You must not modify the array (assume the array is read only).
You must use only constant, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array, but it could be repeated more than once.

给出一个包含n+1个整数的数组,包含1~n(包含n),找出重复的数字

附加条件:
不能修改数组,也就是不能用排序
只能用O(1) 的额外空间,也就是不能用hashset之类的保存数字
runtime小于O(n2),也就是不能用brute force搜索

思路:
本质上是链表中存在环,找环入口的问题。

为什么是链表的环?且把数组中每个数字看作数组下标(因为本来应该是1~n的下标,对应1~n的数字)来看。
以前在链表中走一步是把指针右移,即指针++,
这里的走一步是找到nums中对应下标的数字,即nums[pointer],走两步就是nums[nums[pointer]]。

可以看example1: [1,3,4,2,2]
从下标0开始,nums[0] = 1, 然后nums[1] = 3, nums[3] = 2, nums[2] = 4, nums[4] = 2,
看到这里出现了环,nums[3] == nums[4]。

找到环的入口在142. 链表环中见过,
用快慢指针,快指针每次走两步,慢指针每次走一步,它们相遇就是存在环。
然后慢指针回到起点,快慢指针每次都走一步,它们相遇的地方即是环的入口,也就是重复的元素。

    public int findDuplicate(int[] nums) {
        int n = nums.length;
        int slow = 0;
        int fast = 0;
        
        while(true) {
            slow = nums[slow];
            fast = nums[nums[fast]];
            if(slow == fast) break;
        }
        
        slow = 0;
        
        while(true) {
            slow = nums[slow];
            fast = nums[fast];
            if(slow == fast) break;
        }
        return slow;
    }

参考 Floyd算法

达梦--利用存储过程与定时任务实现数据自动迁移 本文详细介绍了在达梦数据库中如何结合存储过程与定时任务实现数据自动迁移。通过一个电商订单归档的实战案例,阐述了从设计表结构、编写具备异常处理和幂等性的存储过程,到配置DBMS_SCHEDULER定时任务的全流程。该方法能有效替代手动脚本,确保数据同步任务的稳定、准确与自动化执行,适用于报表准备、数据备份等多种场景。 阅读详情

相关推荐

Nordic nRF52832实战:手把手教你搭建智能手环BLE通信框架(附完整代码)

本文详细介绍了如何使用Nordic nRF52832芯片搭建智能手环的BLE通信框架,涵盖芯片优势、协议栈初始化、低功耗广播策略及健康数据服务实现。通过完整代码示例和架构设计,帮助开发者快速掌握蓝牙低功耗通信技术,适用于可穿戴设备开发。

weixin_29192141的博客 250

RTLocating框架:硬件设计迭代的精准定位技术

在芯片设计领域,寄存器传输级(RTL)代码是数字电路行为描述的核心语言,其开发效率直接影响芯片项目的整体周期。传统RTL开发面临的主要挑战在于代码修改时的精准定位问题,尤其在大型SoC设计中更为突出。RTLocating框架通过融合自然语言处理技术与硬件设计知识,实现了从变更需求描述到具体RTL代码块的精准定位。该框架采用多维度编码器融合、动态路由机制等创新技术,显著提升了硬件设计迭代的效率。RTLocating特别适用于功能扩展、微架构优化和错误修复等典型场景,为EDA工具集成提供了高效的解决方案。通过工

weixin_30394981的博客 438

路径规划:D*Lite寻路算法详解

D*Lite详解目录

mkr67n的博客 2万+

[leetcode] 287. Find the Duplicate Number 寻找重复数

Description Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicat...

Learning from the mistakes 406

SPSS_Process—简单&平行&链式中介模型

本篇文章介绍采用SPSS的插件Process对简单中介、链式中介、平行中介模型进行检验的操作方法及结果解读。

m0_54401011的博客 4万+

信创环境下,软件测试如何破局?

毕竟,在自主可控的道路上,每一行通过测试的代码,都在为信创产业的未来添砖加瓦。未来,测试工程师不仅要验证软件在信创环境的可用性,更要基于国产软硬件的特性,推动软件进行 “原生设计”—— 例如,针对国产 CPU 的多核架构优化代码,基于国产数据库的索引机制提升查询效率。某政务云平台的测试数据显示,在 “飞腾芯片 + 麒麟操作系统” 环境下,系统的并发处理能力较传统环境下降约 15%,测试团队通过优化软件的线程调度逻辑,最终将性能损失控制在 5% 以内 —— 这正是信创性能测试的价值所在。

weixin_45608163的博客 887

Find the Duplicate Number寻找重复数(剑指offer,寻找重复的数)

给定一个包含n+ 1 个整数的数组nums,其数字都在 1 到n之间,包括 1 和n,可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。 示例 1: 输入: [1,3,4,2,2] 输出: 2 示例 2: 输入: [3,1,3,4,2] 输出: 3 说明: 不能更改原数组(假设数组是只读的)。 只能使用额外的 O(1) 的空间。 时间...

qq_26410101的博客 790

时间序列预测 | Python实现CNN-LSM模型时间序列预测

时间序列预测 | Python实现CNN-LSM模型时间序列预测 目录时间序列预测 | Python实现CNN-LSM模型时间序列预测基本介绍环境准备程序设计数据处理模型搭建结果分析模型评估总结 基本介绍 这篇文章将带大家通过Tensorflow框架搭建一个基于CNN-LSTM的简单股票价格预测模型,这个模型首先是将一个窗口的股票数据转换为一个2D的图像数据,然后通过CNN进行特征提取。 文中,通过64个filter来进行特征提取,之后通过Relu函数进行激活,接着通过max-pooling进行池化处理,

前程算法屋的博客 5579

Find the Duplicate Number

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, fi

429

UniRx之基本语法格式

想要更好的去学习UniRx,我们最好是先理解UniRx 的语法格式。就像我们去学习英语或者汉语一样,理解了基本的语法规则后,再学其他的就信手拈来了。

TxNet 926

【目标跟踪】基于Kalman滤波实现无人机运动轨迹跟踪附matlab代码

1 简介 在近代控制中,需要对某一特定的运动目标进行跟踪监测,并需要对其下一时间的运动位置,运动方向,速度等信息进行预先估算,才能达到对目标的即时控制.本文简要讨论了用卡尔曼滤波算法对单个目标航迹进行预测,并借助于Matlab仿真工具,对实验的效果进行评估. 2 部分代码 clc; close all; %initial state xo=25; vox=2; %Observations **** % X-Direction Calcula

qq_59747472的博客 4733

Find the Duplicate Number leetcode 287

题目大意:找到数组中唯一的一个重复的数值。时间复杂度要小于O(n^2),不能修改数组了。 发现一个很6的算法,把数组当成一个静态链表,也就是说nums[],数组相当于next[],0为起始节点,节点地址范围就是0-n,一共n+1个节点。 因为数组范围是1-n,所以没有节点next会指向0。

天天烤代码 661

万字长文带你由浅入深夯实ARM汇编基础——汇编指令及寻址方式最全梳理(附示例)!

见到汇编就害怕?读完这篇,扫除汇编拦路虎!!(示例丰富,可做手册,随手查阅!)

车载系统攻城狮 1万+

LeetCode 287. Find the Duplicate Number(找重复数字)

原题网址:https://leetcode.com/problems/find-the-duplicate-number/ Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate nu

James Pan 3115

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

LeetCode //C - 287. Find the Duplicate Number

【代码】LeetCode //C - 287. Find the Duplicate Number。

Made in Code 802

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

287. **Find the Duplicate Number

287. **Find the Duplicate Number https://leetcode.com/problems/find-the-duplicate-number/description/ 题目描述 Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusiv...

珍妮的选择的博客 250

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

Leetcode 287. Find the Duplicate Number

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number,

无名山丘,崛起成峰 1489

leetcode 287. Find the Duplicate Number,数组中找重复的数

287. Find the Duplicate Number Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that th

记忆力不好的博客 2866

leetcode 287: Find the Duplicate Number

Find the Duplicate Number Total Accepted: 1340 Total Submissions: 4766 Difficulty: Hard Given an array nums containing n + 1 integers where each integer is between 1 and n (incl

西施豆腐渣 8802

Java描述 LeetCode,287. Find the Duplicate Number 寻找重复数

两种方法,从循环链表中找出思路

人在江湖 982

[leetcode 287]Find the Duplicate Number

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate element must exist. Assume that there is only one duplicate number,

ER_Plough的专栏 2354

LeetCode 287: Find the Duplicate Number题解(python)

Leetcode 287: Find the Duplicate Number 分类:Binary Search 难度:M 描述:给了一个长度为n + 1的数组,数组中的树大小在1和n之间。证明这个数组中一定有重复的数字,并且把它找出来。 Input: [1,3,4,2,2] Output: 2 Input: [3,1,3,4,2] Output: 3 链接: Find the Duplicate Number. 思路: 在这里首先说一个原理: 抽屉原理.简单来说,就是11个苹果想放进10个或更少的抽屉

Bourns_A的博客 405

[leetcode]287. Find the Duplicate Number

题目链接:https://leetcode.com/problems/find-the-duplicate-number/?tab=Description Given an arraynumscontainingn+ 1 integers where each integer is between 1 andn(inclusive), prove that at least

xiaocong1990的博客 415

LeetCode Top 100 Liked Questions 287. Find the Duplicate Number (Java版; Medium)

welcome to my blog LeetCode Top 100 Liked Questions 287. Find the Duplicate Number (Java版; Medium) 题目描述 Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive),...

littlehaes的博客 258

leetcode 【287 Find the Duplicate Number】【Python】

本题同样让我们找数组中重复的数字,但是给出了很多限制条件。其实leetcode好像对一些限制条件,无法做出判断,我们还是自我严格要求的好哦!首先,第一个不可以改变数组,其实这个就是限制了我们排序,如果排序,然后再遍历一下很快就能找到重复的数字了,时间复杂度O(nlogn),空间复杂度O(1); 其次,空间复杂度O(1),这个限制了我们使用hash查找,因为hash时间复杂度是O(1),但是空间要O

u014251967的博客 2583

[LEETCODE] 287. Find the Duplicate Number

[LEETCODE] 287. Find the Duplicate NumberGiven an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume tha

TonyYang1995的博客 1255
上一篇: leetcode 278. First Bad Version (第一个bad version)
下一篇: leetcode 229. Majority Element II(主元素II)
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值