方法一:(简单容易想,但是不符合O(n))
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
unordered_set<int> hash;
for(auto x: nums) hash.insert(x);
int res = 1;
while(hash.count(res)) res ++;
return res;
}
};
方法二:
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int n = nums.size();
for(int i = 0; i < n; i ++)
{
while(nums[i] <= n && nums[i] > 0 && nums[nums[i] - 1] != nums[i])
swap(nums[i], nums[nums[i] - 1]);
}
for(int i = 0; i < n; i ++)
{
if(nums[i] != i + 1)
return i + 1;
}
return n + 1;
}
};