您的位置:首页 > 其它

[LeetCode] First Missing Positive

2012-10-31 11:34 330 查看
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.

参考这里的解答:http://dl.dropbox.com/u/19732851/LeetCode/FirstMissingPositive.html

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

最后就是可能A[0] == n,这时就要有个特殊情况的处理。

class Solution {
public:
int firstMissingPositive(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i = 0;
while(i < n)
{
if (A[i] == i)
i++;
else
{
if (0 <= A[i] && A[i] < n && A[A[i]] != A[i])
{
int t = A[i];
A[i] = A[A[i]];
A[t] = t;
continue;
}
else
i++;
}
}

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

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