当前位置:网站首页>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;
};
边栏推荐
- 可变长参数
- Promise 在uniapp的简单使用
- poi追加写EXCEL文件
- Is it safe to open an account in Zheshang futures?
- Double pointeur en langage C - - modèle classique
- TP-LINK enterprise router PPTP configuration
- PC easy to use essential software (used)
- Generator parameters incoming parameters
- ROS compilation calls the third-party dynamic library (xxx.so)
- MySQL learning record 10getting started with JDBC
猜你喜欢

Tcp/ip protocol

MySQL learning record 10getting started with JDBC

Detailed explanation of heap sorting

Deep anatomy of C language -- C language keywords

sublime text的编写程序时的Tab和空格缩进问题

深度剖析C语言指针
![[embedded] print log using JLINK RTT](/img/22/c37f6e0f3fb76bab48a9a5a3bb3fe5.png)
[embedded] print log using JLINK RTT

MySQL learning records 12jdbc operation transactions

egg. JS project deployment online server

PC easy to use essential software (used)
随机推荐
堆排序详解
R language uses the principal function of psych package to perform principal component analysis on the specified data set. PCA performs data dimensionality reduction (input as correlation matrix), cus
【嵌入式】Cortex M4F DSP库
电脑F1-F12用途
sublime text中conda环境中plt.show无法弹出显示图片的问题
egg. JS project deployment online server
Charging interface docking tutorial of enterprise and micro service provider platform
Cisp-pte practice explanation
Beijing invitation media
Using pkgbuild:: find in R language_ Rtools check whether rtools is available and use sys The which function checks whether make exists, installs it if not, and binds R and rtools with the writelines
View computer devices in LAN
Delay initialization and sealing classes
What is the role of automated testing frameworks? Shanghai professional third-party software testing company Amway
Marathon envs project environment configuration (strengthen learning and imitate reference actions)
同一局域网的手机和电脑相互访问,IIS设置
The mysqlbinlog command uses
【嵌入式】使用JLINK RTT打印log
On the inverse order problem of 01 knapsack problem in one-dimensional state
JVM performance tuning and practical basic theory - Part 1
移位运算符