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 give 2. The input [1, 2, 0] should give 3.

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的更多相关文章

  1. [LeetCode] First Missing Positive 首个缺失的正数

    Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0]  ...

  2. Leetcode First Missing Positive

    Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0]  ...

  3. 【leetcode】First Missing Positive

    First Missing Positive Given an unsorted integer array, find the first missing positive integer. For ...

  4. 【leetcode】First Missing Positive(hard) ☆

    Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0]  ...

  5. LeetCode题解-----First Missing Positive

    Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0]  ...

  6. Java for LeetCode 041 First Missing Positive

    Given an unsorted integer array, find the first missing positive integer. For example, Given [1,2,0] ...

  7. [LeetCode]题解(python):041-First Missing Positive

    题目来源 https://leetcode.com/problems/first-missing-positive/ Given an unsorted integer array, find the ...

  8. leetcode 41 First Missing Positive ---java

    Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0]  ...

  9. 【First Missing Positive】cpp

    题目: Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2 ...

随机推荐

  1. 为什么全部width:100%浏览器边缘存在留白?

    一般浏览器都给body加了外边距,margin:0应该能解决你所遇到的问题.但你很可能又会遇到其他奇怪的现象,比如说p的行高,在不同浏览器上显示不一致,最根本的解决方案还是重置浏览器默认样式. 可以使 ...

  2. 汉化 的 空指针 bug

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha nulljava.lang.NullPointerException at com.an ...

  3. bzoj5102 [POI2018]Prawnicy 线段树

    $bzoj$跑的太慢了...... 我们考虑用线段树来解决这个问题 考虑扫描线 当扫到左端点$i$时,我们把线段$i$加入线段树 同时,对于每个左端点$i$,我们在线段树上二分出最远的$r$满足$r$ ...

  4. BZOJ.4316.小C的独立集(仙人掌 DP)

    题目链接 \(Description\) 求一棵仙人掌的最大独立集. \(Solution\) 如果是树,那么 \(f[i][0/1]\) 表示当前点不取/取的最大独立集大小,直接DP即可,即 \(f ...

  5. CF961E Tufurama【主席树】

    CF961E Tufurama 题意翻译 题目描述 有一天Polycarp决定重看他最喜爱的电视剧<Tufurama>.当他搜索“在线全高清免费观看Tufurama第3季第7集”却只得到第 ...

  6. python MySQL 获取全部数据库(DATABASE)名、表(TABLE)名

    import MySQLdb #connect try: conn = MySQLdb.connect( host = "localhost", user = "root ...

  7. MySQL命令行工具各功能说明(转)

    MySQL 服务器端使用工具程序 mysqld - SQL 后台程序(即 MySQL 服务器进程).该程序必须启动运行,才能连接服务器来访问数据库. mysqld_safe - 服务器启动脚本,可以通 ...

  8. WPF中删除打开过的图片

    在WPF中,当我们删除打开过的图片时,往往会遇到"...无法删除,文件正在被另一个进程使用"的异常.即使当前文件是打开后关闭过的也不行. 这个问题的原因很简单,是因为WPF的缓存策 ...

  9. MySQL运维开发相关的所有工具

    http://www.ruzuojun.com/topic/592.html   Percona Toolkit 安装使用 http://cenalulu.github.io/mysql/mysql- ...

  10. android 管理手机短信

    为了看代码方便,一边在网上google资料,一边看Android java 源代码. 偶然发现了一个类MmsSmsDatabaseHelper.java,原来android将所有的短信信息都存入了mm ...