博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Algorithm] Find first missing positive integer
阅读量:4677 次
发布时间:2019-06-09

本文共 2891 字,大约阅读时间需要 9 分钟。

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 = 0; i < len; i++) {    let current = arr[i];    while (current >= 0 && current <= len && current !== arr[current]) {      [arr[i], arr[current]] = [arr[current], arr[i]];      current = arr[i];    }  }  console.log(arr);  for (let j = 1; j < len; j++) {    if (arr[j] !== j) {      return j;    }  }  return len;}var arr = [3, -4, 9, 1, 0];const res = first_missing_positive(arr);console.log(res); // 2

 

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 = 1; j < arr.length; j++) {    if (s.has(j)) {      continue;    }    return j;  }}var arr = [3, 4, -1, 1];const res = first_missing_positive(arr);console.log(res); // 2

This is much simpler, but runs in O(N) time and space, whereas the previous algorithm uses no extra space.

转载于:https://www.cnblogs.com/Answer1215/p/10493609.html

你可能感兴趣的文章
htmlparser使用举例
查看>>
[Leetcode]3Sum
查看>>
十四、web基础,用html元素制作web页面
查看>>
简明python_Day8_软件开发流程
查看>>
vhdl verilog
查看>>
LeetCode 6 ZigZag Conversion 模拟 难度:0
查看>>
bootstrap入门-4.排版及其他固定样式
查看>>
WEB安全之解决CC攻击
查看>>
Html5 01(data-attributes、form-types【只在移动端使用】、svg)
查看>>
python之random模块
查看>>
visor 发布
查看>>
nginx 隐藏版本信息
查看>>
百事世界杯之旅
查看>>
Launch VINS-Mono with Realsense D435i in RTAB-Map
查看>>
以一点为中心旋转动画实现,摇摆动画
查看>>
js去除范围内所有标签并显示指定字符串
查看>>
结对项目进度2
查看>>
git + git flow 的简单介绍
查看>>
Servlet详解(四)--Request与Response
查看>>
如果我们想要交换两个数字,就可以使用位运算
查看>>