您的位置:首页 > 其它

[LeetCode] 030: First Missing Positive

2017-09-10 20:48 453 查看
[Problem]

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.

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

// find
for(int i = 0; i < n; ++i){
if(A[i] != i+1){
return i+1;
}
}
return n+1;
}
};
说明:版权所有,转载请注明出处。Coder007的博客
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: