题目描述
给你一个主键清单,该清单无序且每个元素均为整型,每个整数范围为[-999999,999999],请输出首个不在主键清单中的正整数。 e.g: 输入:[8,-1,3,9,5] 输出:1 输入:[0,1,2,3,4,5,6,7] 输出:8
参考代码
#include<stdio.h>
#include<stdlib.h>
#include <vector>
#include <iostream>
using namespace std;
typedef struct
{
int* elem;
int length;
int listsize;
}sqlist;
bool initlist_sq(sqlist& L, int LISTINITSIZE)
{
L.elem = (int*)malloc(LISTINITSIZE * sizeof(int));
if (!L.elem)
return false;
L.length = 0;
L.listsize = LISTINITSIZE;
return true;
}
int cft(int* arr, int arrLen) {
int* ptr = arr;
int tmp;
sqlist La, Lb;
initlist_sq(La, arrLen);
initlist_sq(Lb, arrLen);
La.length = arrLen;
Lb.length = La.length + 1;
int i;
for (i = 0; i < La.length; i++) {
tmp = *ptr;
La.elem[i] = tmp;
ptr++;
}
for (i = 1; i <= Lb.length; i++)
Lb.elem[i] = 0;
for (i = 0; i < La.length; i++)
if (La.elem[i] >= 1)
Lb.elem[La.elem[i]] = 1;
for (i = 1; i <= Lb.length; i++)
if (Lb.elem[i] == 0)
break;
return i;
}
int main()
{
int input[5] = {8,-1,3,9,5 };
int ret = cft(input,5);
cout << ret << endl;
return 0;
}
|