当前位置:网站首页>LeetCode:41. 缺失的第一个正数
LeetCode:41. 缺失的第一个正数
2022-07-06 08:44:00 【Bertil】
给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数。
请你实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案。
示例 1:
输入:nums = [1,2,0]
输出:3
示例 2:
输入:nums = [3,4,-1,1]
输出:2
示例 3:
输入:nums = [7,8,9,11,12]
输出:1
提示:
- 1 <= nums.length <= 5 * 10^5
- -2^31 <= nums[i] <= 2^31 - 1
解题思路
1.首先将nums[i]放到对应的位置,如nums[0] = 1,nums[1] = 2,…,nums[6] = 7
2.然后遍历交换位置之后的数组,判断是否是对应位置,若不是,则直接返回当前索引值 + 1;若全都是,则直接返回nums.length + 1即可
代码
/** * @param {number[]} nums * @return {number} */
var firstMissingPositive = function(nums) {
for(let i = 0; i < nums.length; i++) {
// 循环nums,当前元素在(0,nums.length]之间,并且nums[nums[i]-1] != nums[i],则交换位置
while(nums[i] > 0 && nums[i] <= nums.length && nums[nums[i]-1] != nums[i]) {
const temp = nums[nums[i]-1];
nums[nums[i]-1] = nums[i];
nums[i] = temp;
}
}
for(let i = 0; i < nums.length; i++) {
// 循环交换位置之后的数组,判断第一个缺失的正数
if(nums[i] != i+1) {
return i+1;
}
}
// [1,2,3]
return nums.length + 1;
};
边栏推荐
- 企微服务商平台收费接口对接教程
- R language ggplot2 visualization: place the title of the visualization image in the upper left corner of the image (customize Title position in top left of ggplot2 graph)
- JVM performance tuning and practical basic theory - Part 1
- Crash problem of Chrome browser
- Modify the video name from the name mapping relationship in the table
- Verrouillage [MySQL]
- 深度剖析C语言数据在内存中的存储
- vb.net 随窗口改变,缩放控件大小以及保持相对位置
- Research and investment forecast report of citronellol industry in China (2022 Edition)
- 2022.02.13 - NC003. Design LRU cache structure
猜你喜欢

2022.02.13 - NC002. sort

目标检测——Pytorch 利用mobilenet系列(v1,v2,v3)搭建yolov4目标检测平台

【嵌入式】使用JLINK RTT打印log

swagger设置字段required必填

2022.02.13 - NC003. Design LRU cache structure

Cisp-pte practice explanation

Crash problem of Chrome browser

Promise 在uniapp的简单使用

MySQL learning records 12jdbc operation transactions

Bottom up - physical layer
随机推荐
JVM quick start
TCP/IP协议
R language ggplot2 visualization, custom ggplot2 visualization image legend background color of legend
Warning in install. packages : package ‘RGtk2’ is not available for this version of R
[brush questions] top101 must be brushed in the interview of niuke.com
同一局域网的手机和电脑相互访问,IIS设置
Promise 在uniapp的简单使用
Screenshot in win10 system, win+prtsc save location
China's high purity aluminum target market status and investment forecast report (2022 Edition)
Double pointeur en langage C - - modèle classique
egg. JS project deployment online server
Browser thread
hutool优雅解析URL链接并获取参数
Current situation and trend of character animation
How to effectively conduct automated testing?
[MySQL] lock
堆排序详解
MySQL learning record 11jdbcstatement object, SQL injection problem and Preparedstatement object
Report on Market Research and investment prospects of China's silver powder industry (2022 Edition)
延迟初始化和密封类