当前位置:网站首页>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;
};
边栏推荐
- 角色动画(Character Animation)的现状与趋势
- China vanadium battery Market Research and future prospects report (2022 Edition)
- Golang force buckle leetcode 1020 Number of enclaves
- C语言双指针——经典题型
- C语言深度解剖——C语言关键字
- The network model established by torch is displayed by torch viz
- TP-LINK enterprise router PPTP configuration
- Restful API design specification
- [cloud native topic -45]:kubesphere cloud Governance - Introduction and overall architecture of enterprise container platform based on kubernetes
- JVM performance tuning and practical basic theory - Part 1
猜你喜欢
Precise query of tree tree
After PCD is converted to ply, it cannot be opened in meshlab, prompting error details: ignored EOF
2022.02.13 - 238. Maximum number of "balloons"
[MySQL] log
Sublime text in CONDA environment plt Show cannot pop up the problem of displaying pictures
Navicat Premium 创建MySql 创建存储过程
View computer devices in LAN
堆排序详解
Problems in loading and saving pytorch trained models
TP-LINK enterprise router PPTP configuration
随机推荐
2022.02.13 - NC002. sort
优秀的软件测试人员,都具备这些能力
Promise 在uniapp的简单使用
游戏解包的危害及资源加密的重要性
Sort according to a number in a string in a column of CSV file
Chrome浏览器的crash问题
JS native implementation shuttle box
[cloud native topic -45]:kubesphere cloud Governance - Introduction and overall architecture of enterprise container platform based on kubernetes
Revit 二次开发 HOF 方式调用transaction
After PCD is converted to ply, it cannot be opened in meshlab, prompting error details: ignored EOF
深度剖析C语言指针
Restful API design specification
Simple use of promise in uniapp
【ROS】usb_cam相机标定
[embedded] print log using JLINK RTT
查看局域网中电脑设备
TCP/IP协议
如何有效地进行自动化测试?
To effectively improve the quality of software products, find a third-party software evaluation organization
Verrouillage [MySQL]