LeetCode刷题 fIRST MISSING POSITIVE

Given an unsorted integer array,find missing postive 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 users constant space.

分析如下:

首先,要理解题解:

如果输入是{1,2,3,5},输出是4.

如果输入是{1,2,3,4},输入是5.

如果输入是{1000},输入是1,不是1001.

所以题目是需要你在从1~+无穷的范围中,找到没有在输入数组出现过

的最小的正数。

然后,这道题基本上不太好想,需要借助buctet sort 的思路来考虑。

首先扫描一遍数组,如果某个元素在1-n之间,则把他放入原数组中的

位置,最后扫描到第一个满足A[i]!=i+1的数。更加详细的分析和图片解释可以

看这篇文章的解释。

//思路来自bucket sort 

//8ms

class Solution {

public :

void exchage (int &a,int &b){

int tmp=a;

a=b;

b=tmp;

}

int firstMissingPositive(int A[],int n){

int i=0;

while (i<0){

if (A[i]!=i+1&&A[i]>=1&&A[i]<=n&&A[A[i]-1]!=A[i])

{

exchage(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;

}

};

原文地址:https://www.cnblogs.com/heruonan/p/8366523.html