【leetcode】First Missing Positive

时间:2023-03-09 08:46:14
【leetcode】First Missing Positive

First Missing Positive

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.

通过swap操作,把各个元素swap到相应的位置上,然后再扫描一遍数组,确定丢失的正数的位置
 class Solution {
public:
int firstMissingPositive(int A[], int n) { if(n==) return ; for(int i=;i<n;i++)
{
if(A[i]!=i+&&A[i]<=n&&A[i]>=&&A[i]!=A[A[i]-])
{
swap(A[i],A[A[i]-]);
i--;
}
} for(int i=;i<n;i++)
{
if(A[i]!=i+) return i+; }
return n+; } void swap(int &a,int &b)
{
int tmp=a;
a=b;
b=tmp;
}
};