您的位置:首页 > 其它

leetcode First Missing Positive

2014-06-26 22:11 381 查看
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)并且常数空间,所以需要在原来的数组中做工作。第一个miss的正整数,因为正整数是按照下标的顺序排列的,所以可以利用这点进行交换,
class Solution {
public:
int firstMissingPositive(int A[], int n) {
for(int i=0;i<n;){
if(A[i]>0&&A[i]!=(i+1)&&A[i]<n&&A[i]!=A[A[i]-1]){ //首先确保swap的地方没有越界,之后确保swap双方不一样,否则死循环。A[i]也没没有在最终位置
swap(A[i],A[A[i]-1]);
}
else{
i++;
}
}
for(int i=0;i<n;i++){
if(A[i]!=i+1)
return i+1;
}
return n+1;
}
void swap(int &a,int &b){
int temp=a;
a=b;
b=temp;
}

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