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)
假设所给数组的长度为K,则这个数组最多可存放[1,2,3,4,5,...,k]这k个正整数。
class Solution {
public:
int firstMissingPositive(int A[], int n) {
//把<=0或者>n的位置都置成-1
for(int i=0; i<n; i++){
if(A[i]<=0||A[i]>n)A[i]=-1;
}
//把正整数放置到对应的位置上
for(int i=0; i<n; i++){
if(A[i]>0){
while(A[i]>0 && i!=A[i]-1 && A[A[i]-1]!=A[i]){
int temp=A[i];
A[i]=A[temp-1];
A[temp-1]=temp;
}
if(A[A[i]-1]==A[i] && i!=A[i]-1)A[i]=-1; //如果某些位置上的值重复出现,则需要特殊处理(加入去重处理),例如输入样例[1,1]
}
}
//扫描第一个值<0的位置
for(int i=0; i<n; i++){
if(A[i]<0)return i+1;
}
return n+1;
}
};LeetCode: First Missing Positive [040],布布扣,bubuko.com
LeetCode: First Missing Positive [040]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/26365343