缺失數
Case Time Limit: 3200 MS (Others) / 6400 MS (Java) Case Memory Limit: 256 MB (Others) / 512 MB (Java)
Problem Description
輸入N個整數,求缺失的最小正整數,即1、2、3、...中不存在於這N個整數中的最小數。例如-3、-1、0、1、2、4、6中缺失的最小正整數爲3。注意這N個整數可能無序。
Input
每個輸入文件一組數據。
對每組數據,第一行爲一個整數N(0 <= N <= 10^7),表示整數的個數;
第二行爲N個整數,每個整數的絕對值都不超過10^18。
Output
輸出一個正整數,即缺失的最小正整數。
Sample Input
Sample Output
Author
Source
#include <cstdio>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long LL;
const int MAXN = 10000010;
int n;
LL a[MAXN];
vector<int> vec;
int getFirstMissingPositiveInteger(){
for(int i = 1;i <= n; i++){
while(a[i]>0 && a[i]<=n && a[i] != a[a[i]] ){
swap(a[i],a[a[i]]);
}
}
for(int i=1;i<=n;i++){
if(a[i] != i){
return i;
}
}
return n+1;
}
int main(){
scanf("%d",&n);
for(int i = 1; i <= n; i++){
scanf("%lld",&a[i]);
}
printf("%d\n",getFirstMissingPositiveInteger());
return 0;
}
仍然是複寫晴神答案,我最初嘗試用hash來寫,很快寫完,但數值太大,沒能通過