[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 ...
随机推荐
- luoguP4208 [JSOI2008]最小生成树计数 矩阵树定理
题目大意: 求最小生成树的数量 曾今的我感觉这题十分的不可做 然而今天看了看,好像是个类模板的题.... 我们十分容易知道,记能出现在最小生成树中的边的集合为\(S\) 那么,只要是\(S\)中的边构 ...
- Git 工具的使用,windows平台安装
先谈谈版本控制的一些事 如果你严肃对待编程,就必定会使用"版本控制系统"(Version Control System). 随着信息科技的发展,软件开发已不是小手工作坊,软件的规模 ...
- Loj10166 数字游戏2
题目描述 由于科协里最近真的很流行数字游戏,某人又命名了一种取模数,这种数字必须满足各位数字之和 modN 为 000.现在大家又要玩游戏了,指定一个整数闭区间 [a,b][a,b][a,b],问这个 ...
- BZOJ 2756: [SCOI2012]奇怪的游戏 网络流/二分
2756: [SCOI2012]奇怪的游戏 Time Limit: 40 Sec Memory Limit: 128 MBSubmit: 1594 Solved: 396[Submit][Stat ...
- OPENCV----在APP性能测试中的应用(一)
应用项目: APP的性能测试 应用场景: APP启动速度 视频开播速度 加载速度 等~~ 缘来: 基于APP日志和UiAutomator的测试方案,测试结果不能直白且精确的反应,用户的体验 ...
- CentOS 7编译openssl
# 编译安装zlib库wget http://zlib.net/zlib-1.2.11.tar.gztar -zxvf zlib-1.2.11.tar.gz cd zlib-1.2.11 ./conf ...
- Automatic WordPress Updates Using FTP/FTPS or SSH
Introduction When working with WordPress in a more secure environment where websites are not entirel ...
- MySQL性能诊断与调优 转
http://www.cnblogs.com/preftest/ http://www.highperfmysql.com/ BOOK LAMP 系统性能调优,第 3 部分: MySQL 服务 ...
- PostgreSQL 资源
http://blog.163.com/digoal@126/blog/static/163877040201172183022203/ http://m.oschina.net/u/2426299? ...
- C#引用类型转换的几种方式
本篇体验引用类型转换:子类转换成父类,父类转换成子类,以及不是子父级关系类之间的转换. □ 隐式转换:子类转换成父类 public class Animal { public int _age; pu ...