# 【Leetcode】41. First Missing Positive

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.

***********************************************************************************************************************************************

int firstMissingPositive(vector<int> &nums) //O(n) time O(1) space
{
int size = nums.size();
for (int i = 0; i < size; ++i)
while (nums[i] > 0 && nums[i] <= size && nums[nums[i] - 1] != nums[i])
swap(nums[i], nums[nums[i] - 1]);

for (int i = 0; i < size; i++)
{
if (nums[i] != (i + 1))
return i + 1;
}
return size + 1;
}

int firstMissingPositive(vector<int> &nums) // O(n) time O(n) space
{
if (nums.empty())
return 1;
unordered_map<int, int> map;
int min = -1;
for (size_t i = 0; i < nums.size(); i++)
{
if (nums[i] < 1)
continue;
if (min == -1)
min = nums[i];
if (nums[i] < min)
min = nums[i];
map[nums[i]] = i;
}//建表
if (min == -1 || min > 1)
return 1;
int missing = min + 1;
while (map.find(missing) != map.end())
{
missing++;
}//查表
return missing;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120