您的位置:首页 > 其它

First Missing Positive

2014-12-05 14:31 155 查看
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.

基本上暴力 排序是不行,因为 O(N)的限制 。那么 其实 就是洗牌。。。。因为 数组是连续 的 那么肯定是 0 存1, 1的位置 存2 。。。。 i+1=A[i]。那么就按照 这个洗牌,当 A[A[i]-1]!=A[i], 那么 就 换下位置,然后 遍历一下 找不符合条件的就是第一个 

class Solution {
public:
int firstMissingPositive(int A[], int n) {
for (int i=0; i<n; i++){
int digit=A[i];
while(digit>0 && digit <=n && A[digit-1]!=digit){
swap(A[digit-1],A[i]);
digit=A[i];
}
}
for (int i=0; i<n; i++){
if (i+1!=A[i])
return i+1;
}
return n+1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode