您的位置:首页 > 其它

First missing positive

2013-05-07 01:09 183 查看
题目:

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.

思路: 主要的思想就是把对应的数放到对应的索引上,例如1放到A[1]上,这样只需要O(n)的遍历就能完成,然后用一个O(n)的遍历找第一个没有放到索引上的数返回。

代码:

class Solution  {
public:
int firstMissingPositive(int A[], int n) {

for (int i=0; i<n; ++i)
{
if (A[i] > 0 && A[i] < n)
{
if (A[i]-1 != i && A[A[i]-1] != A[i])
{
int temp = A[A[i]-1];
A[A[i]-1] = A[i];
A[i] = temp;
--i;
}
}
}

for (int j=0; j<n; ++j)
if (A[j]-1 != j)
return j+1;

return n+1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: