[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 ...
随机推荐
- Codeforces Round #448 C. Square Subsets
题目链接 Codeforces Round #448 C. Square Subsets 题解 质因数 *质因数 = 平方数,问题转化成求异或方程组解的个数 求出答案就是\(2^{自由元-1}\) , ...
- luogu4407 [JSOI2009]电子字典 字符串hash + hash表
暴力枚举,然后\(hash\)表判断 复杂度\(O(26 * 20 * n)\) 具体而言 对于操作1:暴力枚举删除 对于操作2:暴力添加,注意添加不要重复 对于操作3:暴力替换,同样的注意不要重复 ...
- luoguP4503 [CTSC2014]企鹅QQ hash
既然只有一位的不同,那么我们可以枚举这一位.... 我们只需要快速地计算去掉某一位的$hash$值.... 由于$hash(S) = \sum s[i] * seed^i$,因此去掉第$i$位的权值只 ...
- 谈应用环境下的TIME_WAIT和CLOSE_WAIT[转]
昨天解决了一个HttpClient调用错误导致的服务器异常,具体过程如下: http://blog.csdn.net/shootyou/article/details/6615051 里头的分析过程有 ...
- Redis Cluster笔记
Redis Cluster .0搭建与使用 介绍: 特性:使用数据分片(sharding)而非一致性哈希(consistency hashing)来实现: 一个 Redis 集群包含 个哈希槽(has ...
- Git_使用GitHub
我们一直用GitHub作为免费的远程仓库,如果是个人的开源项目,放到GitHub上是完全没有问题的.其实GitHub还是一个开源协作社区,通过GitHub,既可以让别人参与你的开源项目,也可以参与别人 ...
- 关于Vue的一些小技巧
前言 用Vue开发一个网页并不难,但是也经常会遇到一些问题,其实大部分的问题都在文档中有所提及,再不然我们通过谷歌也能成功搜索到问题的答案,为了帮助小伙伴们提前踩坑,在遇到问题的时候,心里大概有个谱知 ...
- configure: error: libpam required but missing
安装pam-devel:yum install pam-devel
- 不用windows不会死
不用windows不会死 近期看到win8广告,仅仅要2999元. 事实上他们不知道,不用windows不但不会死,还会活得更好. 不信.你去问问那些非windows用户,他们是不是非常快乐?烦恼非常 ...
- MVC二级联动使用$.getJSON方法
本篇使用jQuery的$.getJSON()实现二级联动. □ View Models 1: namespace MvcApplication1.Models 2: { 3: public cla ...