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. 【差分约束系统/DFS版SPFA】BZOJ3436-小K的农场

    [题目大意] 总共n个农场,有以下三种描述:农场a比农场b至少多种植了c个单位的作物,农场a比农场b至多多种植了c个单位的作物,农场a与农场b种植的作物数一样多.问是否有可能性. [思路] 农场a比农 ...

  2. 浅析SDWebImage

    浅析SDWebImage 在日常的开发过程中,如果去优雅的访问网络的图片并去管理每个工程必须要面对的问题,如果想要在工程里面提供易用.简洁.方便管理的解决方案还是很有挑战的,毕竟还要兼顾图片文件的缓存 ...

  3. [POI2012]Salaries

    题目大意: 给定一棵n带权树,每个点的权值在[1,n]范围内且互不相等,并满足子结点的权值一定小于父结点. 现在已知一个包含根结点的联通块中个点的权值,求剩下哪些点的权值能够被求出,并求出这些权值. ...

  4. java集合之二(collection架构)

    转载请注明出处:http://www.cnblogs.com/skywang12345/p/3308513.html 首先,我们对Collection进行说明.下面先看看Collection的一些框架 ...

  5. Codeforces Round #295 (Div. 2)B - Two Buttons BFS

    B. Two Buttons time limit per test 2 seconds memory limit per test 256 megabytes input standard inpu ...

  6. spring---transaction(2)---源代码分析(事务的定义TransactionDefinition)

    写在前面 事务属性通过TransactionDefinition接口实现定义,主要有事务隔离级别.事务传播行为.事务超时时间.事务是否只读. public interface TransactionD ...

  7. MySQL Proxy 实现MySQLDB 读写分离

    一.简述 MySQL Proxy是一个处于你的client端和MySQL server端之间的简单程序,它可以监测.分析或改变它们的通信.它使用灵活,没有限制,常见的用途包括:负载平衡,故障.查询分析 ...

  8. 查看是否安装.NET Framework、.NET Framework的版本号、CLR版本号

    查看是否安装.NET Framework→%SystemRoot%\System32→如果有mscoree.dll文件,表明.NET Framework已安装 查看安装了哪些版本的.NET Framw ...

  9. MVC中使用AngularJS-01,基本

    Angularjs是一个前端的Javascript MVC 库和框架,使前端得到更好的设计.维护和测试.它的核心特性有:MVC.双向数据绑定.指令和语义化标签.模块化工具.依赖注入.HTML模板,以及 ...

  10. MVC控制器传递多个Model到视图,使用ViewData, ViewBag, 部分视图, TempData, ViewModel, Tuple

    从控制器传递多个Model到视图,可以通过ViewData, ViewBag, PartialView, TempData, ViewModel,Tuple等,本篇逐一体验.本篇源码在github. ...