Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0]
return 3
,
and [3,4,-1,1]
return 2
.
Your algorithm should run in O(n) time and uses constant space.
Subscribe to see which companies asked this question
思路:利用hashmap,记录三个map 分别代表原本数组,加1之后的数组,以及减1之后的数组。通过+1 -1找到最小的不在原本数组中的最小的正数,然后再与负数中绝对值最小的数进行比较,若负数绝对值更小,则置为1。若正数中不包含1则返回1,否则返回+1 -1中的最小数。
代码如下:
int firstMissingPositive(vector<int>& nums) {
map<int, int> m;
map<int, int> m1;
map<int, int> m2;
if (nums.size() == 0){
return 1;
}
for (int i = 0; i < nums.size(); i++)
{
m[nums[i]]++;
m1[nums[i]+1]++;
m2[nums[i]-1]++;
}
map<int, int>::iterator it;
int temp = 10000;
int re = 1;
// m1+1 m2-1 对应都为非负的情况
for (it = m1.begin(); it != m1.end(); ++it)
{
//找一个m1中最小的然后不在m中
if (it->first > 0&&it->first<=temp){
if (m.find(it->first) == m.end()){
temp = it->first;
}
}
}
for (it = m2.begin(); it != m2.end(); ++it)
{
//找一个m2中最小的然后不在m中
if (it->first > 0 && it->first <= temp){
if (m.find(it->first) == m.end()){
temp = it->first;
}
}
}
//将负数专门挑出来处理
for (it = m.begin(); it != m.end(); ++it)
{
//找一个m1中最小的然后不在m中
if (it->first < 0){
int len = -1 * it->first;
if (len < temp){
if (m.find(1) == m.end()){
temp = 1;
}
}
}
}
//如果正数中不包含1则返回1
if (m.find(1) == m.end()){
temp = 1;
}
//若存在负数 则判断绝对值 绝对值小的负数则对应 1 其他视作正数
re = temp;
return re;
这里还有个更加高效的算法,网址如下:
http://www.cnblogs.com/dollarzhaole/archive/2013/08/07/3243495.html