[LeetCode] 030: First Missing Positive

来源:互联网 发布:js隐藏菜单栏 编辑:程序博客网 时间:2024/06/17 20:17
[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的博客