问题描述
Given an unsorted integer array, find the first missing positive integer.
For example,
Given[1,2,0]
return3
,
and[3,4,-1,1]
return2
.
Your algorithm should run in \(\Theta(n)\) time and uses constant space.
思路
方法一:
由于时间要求是\(\Theta(n)\),所以不能采用排序算法,我最先想到的是利用hash table
来辅助求解。时间上能满足要求,空间的要求是\(\Theta(n)\),似乎有些不符合题意。
方法二:
可以利用已经给出的nums数组,用其数组的下标
作为标记,而用数组元素的值
作为hash函数的key。这样就不需要申请额外的空间了,可以直接在nums数组上做hash操作。但是nums数组的值被改变了。
Code
方法一代码:
|
|
方法二代码:
其中注意一些细节的处理:
- nums数组预先push_back(0)
- 对于负数和大于n的数,将其置为0
- 找first missing positive时,从数组的下标1开始找
|
|