您的位置:首页 > 其它

LeetCode--first-missing-positive

2018-01-16 13:36 453 查看


题目描述

Given an unsorted integer array, find the first missing positive integer.

For example,

Given[1,2,0]return3,

and[3,4,-1,1]return2.

Your algorithm should run in O(n) time and uses constant space.
分析:利用数组的index来作为数字本身的索引,把正数按照递增顺序依次放到数组中。即让A[0]=1, A[1]=2, A[2]=3, ... , 这样一来,最后如果哪个数组元素违反了A[i]=i+1即说明i+1就是我们要求的第一个缺失的正数。对于那些不在范围内的数字,我们可以直接跳过,比如说负数,0,或者超过数组长度的正数,这些都不会是我们的答案。

与剑指offer中的数组中重复的数类似

class Solution {
public:
int firstMissingPositive(int A[], int n)
{
for(int i = 0; i < n; ++ i)
while(A[i] > 0 && A[i] <= n && A[A[i] - 1] != A[i])
swap(A[i], A[A[i] - 1]);

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

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