未出现的最小正整数问题;
整体思路一:排序 + 去重,得到无重复的升序序列;
遍历升序序列的过程中中,正整数必定是依次相邻的,倘若不满足此情况,则说明中间相隔一个正整数,由于遍历顺序,必定对应最小正整数;
最后考虑一些特殊情况与边界情况即可;
整体思路二:桶思想,空间换时间,由于题目要求的限制,最大可能出现的正整数为n,直接开辟n+1大小的数量记录存在情况;
// 法一:
#include <stdio.h>
typedef int Elemtype;
Elemtype a[100];
void quick_sort(Elemtype q[], int l, int r) { // l与r代表下标;
if (l >= r) return;
int i = l - 1, j = r + 1;
Elemtype x = q[l + r >> 1];
while (i < j) {
do i ++; while (q[i] < x);
do j --; while (q[j] > x);
if (i < j) {
int temp = q[i];
q[i] = q[j];
q[j] = temp;
}
}
quick_sort(q, l, j); quick_sort(q, j + 1, r);
}
int del_same(Elemtype q[], int n) {
int i = 0;
for (int j = 1; j < n; j ++)
if (q[i] != q[j]) q[++ i] = q[j];
return i + 1;
}
Elemtype FindMinN(Elemtype a[], int n) {
quick_sort(a, 0, n - 1);
int m = del_same(a, n);
int i = 0;
while (a[i] <= 0 && i < m) i ++;
if (i >= m || a[i] != 1) return 1;
// 此时i指向的元素为1;
int j = i + 1;
while (j < m) {
if (a[j] == a[i] + 1) i ++, j ++;
else return a[i] + 1;
}
if (j == m) return a[i] + 1;
} // Time: O(n + nlogn) Space: O(logn),即快排的temp辅助变量;
int main() {
int n; scanf("%d", &n);
for (int i = 0; i < n; i ++) scanf("%d", &a[i]);
printf("%d\n", FindMinN(a, n));
return 0;
}
// 法二:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int a[100];
int MinN(int q[], int n) {
int *t = (int *)malloc((n + 2) * sizeof(int));
memset(t, 0, sizeof(int) * (n + 2));
for (int i = 0; i < n; i ++)
if (q[i] > 0) t[q[i]] ++;
for (int i = 1; i <= n + 1; i ++)
if (t[i] == 0) return i;
}
int main() {
int n; scanf("%d", &n);
for (int i = 0; i < n; i ++) scanf("%d", &a[i]);
printf("%d\n", MinN(a, n));
return 0;
}