41. First Missing Positive[hard]
- Total Accepted: 74444
- Total Submissions: 303858
- Difficulty: Hard
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.
很简单的题目:找出第一个没出现的正整数。
设n为输入的vector的size,易得:大于n+1的数不可能是没出现的正整数
思想:先处理掉所有的负数,以后每出现一个整数就将它对应的格子增添一个负号。最后看按顺序哪个格子先没有负号,就少了哪个正整数。
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
nums.push_back(0);
for(int i = 0 ; i < nums.size() ; i++ )
if( nums[i] <= 0 )
nums[i] = nums.size()+1;
for(int i = 0 ; i < nums.size() ; i++ )
{
int cnt = abs(nums[i]);
if(cnt >= nums.size())continue;
if( nums[cnt] > 0 )
nums[cnt] = -nums[cnt];
}
for(int i = 1 ; i < nums.size() ; i++ )
if( nums[i] > 0 )
return i;
return (int)nums.size();
}
};