[Algorithm] Find first missing positive integer
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input
[3, 4, -1, 1]
should give2
. The input[1, 2, 0]
should give3
.You can modify the input array in-place.
Our lives would be easier without the linear time constraint: we would just sort the array, while filtering out negative numbers, and iterate over the sorted array and return the first number that doesn't match the index. However, sorting takes O(n log n), so we can't use that here.
Clearly we have to use some sort of trick here to get it running in linear time. Since the first missing positive number must be between 1 and len(array) + 1 (why?), we can ignore any negative numbers and numbers bigger than len(array). The basic idea is to use the indices of the array itself to reorder the elements to where they should be. We traverse the array and swap elements between 0 and the length of the array to their value's index. We stay at each index until we find that index's value and keep on swapping.
By the end of this process, all the first positive numbers should be grouped in order at the beginning of the array. We don't care about the others. This only takes O(N) time, since we swap each element at most once.
Then we can iterate through the array and return the index of the first number that doesn't match, just like before.
function first_missing_positive(arr) {
/**
* The idea is put the number in the arr to its index position
* [1,-1,4,2] --> [-1,1,2,null,4]
* The first missing positive number must be between 1 ~ arr.length + 1
* after swapping array in place, then we can check arrocding to index,
* to find the first missing array. O(N)
*/ const len = arr.length;
for (let i = ; i < len; i++) {
let current = arr[i];
while (current >= && current <= len && current !== arr[current]) {
[arr[i], arr[current]] = [arr[current], arr[i]];
current = arr[i];
}
}
console.log(arr);
for (let j = ; j < len; j++) {
if (arr[j] !== j) {
return j;
}
}
return len;
} var arr = [, -, , 1, 0]; const res = first_missing_positive(arr);
console.log(res); //
Another way we can do this is by adding all the numbers to a set, and then use a counter initialized to 1. Then continuously increment the counter and check whether the value is in the set.
function first_missing_positive(arr) {
const s = new Set(arr);
for (let j = ; j < arr.length; j++) {
if (s.has(j)) {
continue;
}
return j;
}
} var arr = [, , -, ]; const res = first_missing_positive(arr);
console.log(res); //
This is much simpler, but runs in O(N) time and space, whereas the previous algorithm uses no extra space.
[Algorithm] Find first missing positive integer的更多相关文章
- [LeetCode] First Missing Positive 首个缺失的正数
Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0] ...
- Leetcode First Missing Positive
Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0] ...
- 【leetcode】First Missing Positive
First Missing Positive Given an unsorted integer array, find the first missing positive integer. For ...
- 【leetcode】First Missing Positive(hard) ☆
Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0] ...
- LeetCode题解-----First Missing Positive
Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0] ...
- Java for LeetCode 041 First Missing Positive
Given an unsorted integer array, find the first missing positive integer. For example, Given [1,2,0] ...
- [LeetCode]题解(python):041-First Missing Positive
题目来源 https://leetcode.com/problems/first-missing-positive/ Given an unsorted integer array, find the ...
- leetcode 41 First Missing Positive ---java
Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0] ...
- 【First Missing Positive】cpp
题目: Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2 ...
随机推荐
- 「HNOI2018」转盘
「HNOI2018」转盘 现场推出了大部分结论但是只写了 \(40\) 分暴力,被贺指导踩爆,现在还有点怀念 HNOI2018 贺指导对着镜子荒野行动的日子,那几天他云球迷瞎**指点篮球,被送上指导称 ...
- [BZOJ5298][CQOI2018]交错序列(DP+矩阵乘法)
https://blog.csdn.net/dream_maker_yk/article/details/80377490 斯特林数有时并没有用. #include<cstdio> #in ...
- [BZOJ5287][HNOI2018]毒瘤(虚树DP)
暴力枚举非树边取值做DP可得75. 注意到每次枚举出一个容斥状态的时候,都要做大量重复操作. 建立虚树,预处理出虚树上两点间的转移系数.也可动态DP解决. 树上倍增.动态DP.虚树DP似乎是这种问题的 ...
- 随笔idea-辗转落户cnblogs
辗转了几个blog,也用了自己域名2年,感觉忙起来,可能没有那么多时间去维护自己的域: 其他地方的blog也不在一块,思虑许久后,来到cnblogs:
- hash课堂测试补分博客
题目要求: 开放地址法: 概念: 所谓的开放定址法就是一旦发生了冲突,就去寻找下一个空的散列地址,只要散列表足够大,空的散列地址总能找到,并将记录存入. 它的公式为: 解题过程(在下图中): 拉链法: ...
- 拆分Cocos2dx渲染部分代码
纹理实现 思想 这个是Cocos2dx的渲染部分的最基本的实现,被我拆分到mac上,但是并不是用的EGLContext,而是搭配glfw,还有soil第三方图形库. 实现 // // main.cpp ...
- Git_简介
Git是什么? Git是目前世界上最先进的分布式版本控制系统(没有之一). Git有什么特点?简单来说就是:高端大气上档次! 那什么是版本控制系统? 如果你用Microsoft Word写过长篇大论, ...
- configure: error: lzo enabled but missing
注意:yum安装的无效,需要手动下载源码安装. wget http://www.oberhumer.com/opensource/lzo/download/lzo-2.06.tar.gz tar zx ...
- WindowsPhone&Windows8.1&Windows8&Unity3d 填坑日记
近期的游戏开发大体上接近尾声,总结了不少关于Unity3d面向Windows几大平台开发时遇到的各种坑以及怎样填坑的经验.总的来说,Windows8.1 Windows8/RT以及WindowsPho ...
- ICD2 VPP limiter for new PIC microcontrollers.
http://www.circuitsathome.com/mcu/pic_vpp_limiter VOUT = 2.5V * ( 1 + 24/10 ) = 2.5 * 3.4 = 8.5V New ...