41. First Missing Positive

problem description

Given an unsorted integer array, find the smallest missing positive integer.

Example 1:

Input: [1,2,0]
Output: 3

Example 2:

Input: [3,4,-1,1]
Output: 2

Example 3:

Input: [7,8,9,11,12]
Output: 1

Note:

Your algorithm should run in O(n) time and uses constant extra space.

algorithm thought

得到第一个缺失的正数,由于不需要考虑负数,这里可以很好地用数组下标对应相应的数。一次遍历将相应的数填入对应的下标当中。最后再次遍历数组,找到第一个缺失的数。

code

algorithm analysis

一次遍历数组,时间复杂度O(n)。没有用额外空间存储数据,空间复杂度是O(1)。符合要求

Last updated