LeetCode 41. First Missing Positive

Twincat Scopeview录波中的Ringbuffer设置技巧与常见问题解决 本文深入解析了倍福Twincat Scopeview录波功能中Ringbuffer(环形缓冲区)的核心设置技巧与常见问题解决方案。针对数据丢失、触发时机不准等痛点,详细阐述了缓冲区大小、预触发样本、采样率等关键参数的优化配置,并提供了多通道同步、自动诊断等实战应用指南,帮助工程师高效捕捉和分析PLC数据。 阅读详情

41. First Missing Positive

Given an unsorted integer array, find the first missing positiveinteger.

For example,
Given 
[1,2,0] return 3,
and 
[3,4,-1,1] return 2.

Your algorithm should run in O(n)time and uses constant space.

题目要求寻找第一个丢失的正数。

看题没思路-----苦思未果看题解去

然后我就说说我看的这两种解:

第一种比较正规:

         

大题思路就是首先将正和负的分成两份---直接过滤可以:
                   If(nums[i]>0)nums[n++]=nums[i];
         然后就是对前n个数遍历一边并对在[1,n]之间的数tmp=nums[i]对应的下标 nums[tmp-1] 的数变成负数。
         最后在遍历一遍查看那个(i<n)第一个非负数即时结果。

         代码

 

public class Solution{
	public int firstMissingPositive(int[] nums){
		int n=0;
		for(int i=0;i<nums.length;i++)
			if(nums[n]>0) nums[n++]=nums[i];
		int res=n,tmp;
		for(int i=0;i<n;i++){
			tmp=Math.abs(nums[i]);
			if(tmp<=n) nums[tmp]=-Math.abs(nums[tmp]);
		}
		for(int i=0;i<n;i++){
			if(nums[i]>0) {res=i+1;break;}
		}
		return res;
	}
}

 

第二种有点脑筋急转弯的感觉

         

遍历一遍所有的数tmp=nums[i],当tmp>0时 将交换下标为tmp-1和i 的数即swap(nums,tmp,i);
         最后遍历一遍所有数查到nums[i]!=i+1的即为结果.

代码:

public class Solution {
    public int firstMissingPositive(int[] nums) {
    	for(int i=0;i<nums.length;++i)
    		// if(nums[i]>0&&nums[i]<=nums.length)--->this will be wrong when the nums[i] is big
    		// for example {3,4,-1,1}
    		while(nums[i]>0&&nums[i]<=nums.length&&nums[nums[i]-1]!=nums[i])
    			swap(nums,i,nums[i]-1);
   		for(int i=0;i<nums.length;++i)
   			if(nums[i]!=i+1)
   				return i+1;
   		return nums.length+1;
    }
    public void swap(int[] nums,int i,int j){
    	int tmp=nums[i];
    	nums[i]=nums[j];nums[j]=tmp;
    }
}



【用unity实现100个游戏之7】实现一个类《杀戮尖塔》的卡牌回合制游戏(附项目源码) 阅读详情

相关推荐

ESP32连接OneNet云平台实现多设备联动控制完整示例

通过esp32连接onenet云平台,实现远程设备间的智能联动控制,利用MQTT协议完成数据通信,esp32连接onenet云平台后可高效稳定地上传与下发指令,提升物联网系统响应速度与自动化水平。

weixin_42360733的博客 547

Leetcode 41. First Missing Positive

Leetcode 41. First Missing Positive 算法: Check if 1 is present in the array. If not, you’re done and 1 is the answer. If nums = [1], the answer is 2. Replace negative numbers, zeros, and numbers larger than n by 1s. 检查1是否存在,不存在返回1。如果1存在,且数组只有一个元素,则返回2。把所有0

weixin_43876597的博客 295

驯服电源尖峰:从BUCK/BOOST环路剖析到高di/dt噪声的实战抑制

本文深入探讨了电源系统中高di/dt噪声的产生机制及抑制方法,通过BUCK/BOOST电路的环路分析,揭示了电流路径不连续导致的电压尖峰问题。文章提供了实用的PCB布局技巧和噪声抑制策略,包括最短回路原则、铺铜优化和过孔阵列战术,帮助工程师有效降低EMI噪声,提升电源系统的稳定性。

weixin_29587015的博客 273

Leetcode 41 First Missing Positive

Leetcode 41 First Missing Positive题目思路代码 题目 Given an unsorted integer array, find the smallest missing positive integer. Example 1: Input: [1,2,0] Output: 3 Example 2: Input: [3,4,-1,1] Output: 2 Example 3: Input: [7,8,9,11,12] Output: 1 Follow up: Y

weixin_43796689的博客 209

FPGA优质开源项目 – UDP万兆光纤以太网通信

本文开源一个FPGA项目:UDP万兆光通信。文章末尾有该工程源码获取方式,有需要的小伙伴可以点赞、分享支持一下~

cjx_csdn的博客 4766

SpringBoot+Vue企业级开源聚合支付系统!支持30+款支付平台,只需配置商户证书就能直接使用!

一款开源SAAS支付系统推荐

技术Z先生的博客 2720

LeetCode41——First Missing Positive

LeetCode41——First Missing Positive 题意: 在序列中找到第一个没有出现的正整数。 我的方法比较笨,后来提交过后通过的确时间效率非常低。 首先,排序、去重。 然后对这个有序序列进行迭代: 找到正整数开始的索引i,从这个索引开始,该序列的数后面应该是按 1 2 3 4 5 6 7...这样的顺序来排列。 所以对于从索引i开始的每一个元素nums[

上善若水 607

FoundationPose复现及Realsense应用

FoundationPose是一个统一的基础模型,用于6D对象姿态估计和跟踪,支持基于模型和无模型的设置。在测试时可以立即应用于未见过的新对象,无需微调,只要给出其CAD模型,或者捕获少量RGBD参考图像。得益于统一框架,下游姿态估计模块在两种3D模型设置中都是相同的,当没有CAD模型时,使用神经隐式表示进行高效的新视角合成。通过大规模合成训练,辅以大型语言模型(LLM)、一种基于transformer的新架构和对比学习公式,实现了强大的泛化能力。

m0_56661101的博客 1万+

LeetCode No.41 First Missing Positive 题解

LeetCode No.41 First Missing Positive 题解题目描述 Given an unsorted integer array, find the first missing positive integer. For example, Given[1,2,0] return 3, and [3,4,-1,1] return 2. You

Guo15331092的博客 502

海康网口相机不能被flexscan3d识别到MVS版本为4.6.1,flex为3.3.24在MVS中能够检测到,但是在flex中只能看到电脑自带相机,如何解决?

🏆本文收录于 《全栈 Bug 调优(实战版)》 专栏。专栏聚焦真实项目中的各类疑难 Bug,从成因剖析 → 排查路径 → 解决方案 → 预防优化全链路拆解,形成一套可复用、可沉淀的实战知识体系。无论你是初入职场的开发者,还是负责复杂项目的资深工程师,都可以在这里构建一套属于自己的「问题诊断与性能调优」方法论,助你稳步进阶、放大技术价值 。

**My Coding Family** 1043

把数据库事务边界握在手里:ABAP 里的 COMMIT CONNECTION 与 ROLLBACK CONNECTION 深度拆解

与表面是两条很短的语句,背后却牵动了连接管理、数据库 LUW、SAP LUW、隐式提交、游标生命周期、GTT 平台差异等一整片工程现实。把它们用对,你就能在不破坏主业务事务的前提下,实现跨库写入、审计落库、隔离型日志、数据集成落地等一系列“看似矛盾”的目标;用错了,它们也会悄无声息地制造一致性缺口,让问题在高峰期以 dump 或数据异常的方式爆出来。

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

LeetCode刷题:41. First Missing Positive

LeetCode刷题:41. First Missing Positive 原题链接:https://leetcode.com/problems/first-missing-positive/ Given an unsorted integer array, find the smallest missing positive integer. Example 1: Input: [1,2...

梅森上校的博客 业精于勤荒于嬉,形成于思毁于随。 248

从 CDS 接口到 ABAP 运行时,深入理解 SAP RAP Custom Entity

CDS Custom Entity 是一种非 SQL、瞬态的 CDS 实体,不依赖 HANA SQL 读取数据,而是通过 ABAP 类实现查询逻辑(如 RFC、OData、BAPI 等)。它在 CDS 层定义数据契约(字段、键、关联、注解),由 @ObjectModel.query.implementedBy 指向实现 IF_RAP_QUERY_PROVIDER~SELECT 的类,真正执行数据获取。适用于无法用 SQL 表达的数据源,如远程系统或 API。其核心是“接口 + 实现”模式,运行时由 RAP

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

leetcode 41. First Missing Positive

leetcode 41. First Missing Positive  今天上午做了两个0-n  排序的问题,排序关键所在于swap public class Solution { public int firstMissingPositive(int[] nums) { int len = nums.length; int i=0;

独钓寒江雪 452

jre9下载 jdk9

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

深度学习工具包 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 (41) First Missing Positive

Leetcode (41) First Missing Positive Given an unsorted integer array, find the first missing positive integer. For example, Given [1,2,0] return 3, and [3,4,-1,1] return 2. Your algor

nevermorezjh的专栏 371

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

[LeetCode]41. First Missing Positive

41. First Missing Positive 题目要求找出数组中第一个缺失的正数。难点在与时间复杂的要求O(n),空间复杂度要求O(1)。又是一道不会做抄答案的题目。 思路是把遇到的每一个数放到元数组中排序的位置。 class Solution { public: int firstMissingPositive(vector&lt;int&gt;&amp; nums) ...

JOHZEN 279

LeetCode 41---First Missing Positive

题目链接: LeetCode 41—First Missing Positive AC代码:public class Problem41 { public static void main(String[] args) { // TODO Auto-generated method stub int[] a={1}; System.out.p

调包侠 603

Leetcode 41. First Missing Positive (cpp)

题目 解法1: 首先是时间复杂度O(1),空间复杂度O(n)的解法。关键在于答案一定会在1~n+1中产生,n为数组长度。那么先保存出现过的num,然后遍历1到n+1,找第一个没有出现的即可 class Solution { public: int firstMissingPositive(vector<int>& nums) { unordered_map<int,int> seen; for(int i=0;i<nums.si

qq_37821701的博客 332

Leetcode1-100: 41. First Missing Positive

Leetcode1-100: 41. First Missing Positive问题描述解题思路implement 1implement 2代码实现implement 1implement 2分析后记 问题描述 题目要求: 输入一个整形数组,输出里面缺失的最小的正整数。 解题思路 由于题目中要求了时间复杂度是O(n),还要求空间复杂度是常数,所以这题变得难度大了很多。但是首先分析一下如果去掉这些要求,可以用一个额外的数组来作为flag表示状态的话,这题就简单了很多,注意:假设数组有n个元素,那么最后的结

Y123iwantit的博客 268

LeetCode题目:41. First Missing Positive

LeetCode题目:41. First Missing Positive 原题链接:https://leetcode.com/problems/first-missing-positive/description/ 解题思路:(此题数据限制的不是很严格,用sort快排对数组排序,然后遍历数组,也可以过。)实际上,题目所说的O(1)并不包含输入的数组大小,因此可以改变输入的数组来实现O(n)的复

MyCodecOdecoDecodE的博客 323

【Leetcode】41. 缺失的第一个正整数(First Missing Positive)

Leetcode - 41 First Missing Positive (Hard) Input: [3,4,-1,1] Output: 2 public int firstMissingPositive(int[] nums) { int i = 0; while (i < nums.length) { if (nums[i] >= 1 &amp...

厉兵秣码 367

[Leetcode][Python]41: First Missing Positive

# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com'41: First Missing Positivehttps://oj.leetcode.com/problems/first-missing-positive/Given an unsorted integer array, find the first missi...

aaron7909的博客 270

【leetcode】41. First Missing Positive(缺失的第一个正数)

【leetcode】41. First Missing Positive(缺失的第一个正数) 41. First Missing Positive Given an unsorted integer array, find the smallest missing positive integer. Example 1: Input: [1,2,0] Output: 3 Example 2: ...

描绘自己的王国…… 291

LeetCode(41) First Missing Positive

题目如下: A peak element is an element that is greater than its neighbors. Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. The array may contain multiple peaks,

BUILD 3688
上一篇: freopen---重定向文件流----解决刷oj时手动输入的烦恼
下一篇: LeetCode 42. Trapping Rain Water
朔北冥
博客等级 码龄11年 14粉丝 27原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值