[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 ...
随机推荐
- BZOJ 2466 [中山市选2009]树(高斯消元)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=2466 [题目大意] 给定一棵树,每个节点有一盏指示灯和一个按钮.如果节点的按扭被按了, ...
- 【差分约束系统/SPFA】POJ3169-Layout
[题目大意] n头牛从小到大排,它们之间某些距离不能大于一个值,某些距离不能小于一个值,求第一头牛和第N头牛之间距离的最大值. [思路] 由题意可以得到以下不等式d[AL]+DL≥d[BL]:d[BD ...
- TCP的建立和终止 图解
前言 在没有理解TCP连接是如何建立和终止之前,我想你可能并不会使用connect,accept,close这三个函数并且使用netstat程序来调试应用.所以掌握TCP连接的建立和终止势在必行. 三 ...
- Codeforces #254 div1 B. DZY Loves FFT 暴力乱搞
B. DZY Loves FFT 题目连接: http://codeforces.com/contest/444/problem/B Description DZY loves Fast Fourie ...
- Codeforces Round #298 (Div. 2) A. Exam 构造
A. Exam Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/534/problem/A Des ...
- jconsole监控上Linux上的JVM
说明: 首先JConsole这个是JDK里面自带的工具 在JAVA_HOME/bin目录下,今天主要测试远程监控JVM 第一步:设置好需要远程机器的Tomcat 修改Tomcat下的配置文件:/us ...
- DEX 可视化查阅
参考: http://bbs.pediy.com/thread-208828.htm 010 Editor 下载地址: http://www.sweetscape.com/download/ //-- ...
- j.u.c系列(01) ---初探ThreadPoolExecutor线程池
写在前面 之前探索tomcat7启动的过程中,使用了线程池(ThreadPoolExecutor)的技术 public void createExecutor() { internalExecutor ...
- POJ 3580 SuperMemo (splay tree)
SuperMemo Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 6841 Accepted: 2268 Case Ti ...
- Android字体简述
Android是一个典型的Linux内核的操作系统.在Android系统中,主要有DroidSans和DroidSerif两大字体阵营,从名字就可以看出来,前者是无衬线字体,后者是衬线字体.具体来说, ...