[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 1419】1419: Red is good (概率DP)
1419: Red is good Time Limit: 10 Sec Memory Limit: 64 MBSubmit: 807 Solved: 343 Description 桌面上有R张 ...
- [Arc079F] Namori Grundy
[Arc079F] Namori Grundy 题目大意: 一个有向弱联通环套树. 一个点的sg值等于出边连向点的sg值的mex. 试问是否有办法给每个点分配sg值? 试题分析 题目大意把一些难点跳过 ...
- Codeforces Round #FF (Div. 1) B. DZY Loves Modification 优先队列
B. DZY Loves Modification 题目连接: http://www.codeforces.com/contest/446/problem/B Description As we kn ...
- Codeforces Round #254 (Div. 1) D. DZY Loves Strings hash 暴力
D. DZY Loves Strings 题目连接: http://codeforces.com/contest/444/problem/D Description DZY loves strings ...
- ASP.NET 构建高性能网站 第3篇
HTTP请求的优化 在一个网页的请求过程中,其实整个页面的html结构(就是页面的那些html骨架)请求的时间是很短的,一般是占整个页面的请求时间的10%-20%.在页面加载的其余的时间实际上就是在加 ...
- GoodSync 同步 对比 备份
单向/双向皆可,针对任何一侧的文件进行处理,两侧文件都进行更新 文件同步 的操作过程是:确保两处或多处包含完全一致.及时更新 的各种文件.当对某一处进行文件添加.更改或删除,则同步操作将对对应的 另一 ...
- C#程序集系列07,篡改程序集
以下几个方面用来区分不同的程序集:○ 程序集名称:Name○ 程序集版本:Version○ 程序集公匙: Public Token○ 程序集文化:Culture 如果没有很严格地按照上面的几个方面来创 ...
- SpringBoot 使用小技巧合集
原文:https://my.oschina.net/xiedeshou/blog/1926191 设置网站图标 原来我们在使用tomcat开发时,设置网站图片时,即icon图标时,一般都是直接替换ro ...
- C#Arcengine通过坐标点生成面(环形)
来自:http://www.cnblogs.com/lee24789229/p/5481978.html 通过传入坐标点,返回几何图形,此代码部分可以生成环形面. 方法一 private IGeome ...
- Ext Form
表单Ext.form.FormPanel 1.表单 对于传统的b/s应用来说,数据录入元素是放在表单<form>标签里面的.而对于ExtJS应用来说,则可以直接使用FormPanel控件来 ...