https://pintia.cn/problem-sets/994805342720868352/problems/994805343463260160
此题用Java始终会超时,不值是否有不超时解法
import java.io.*;
import java.util.HashSet;
import java.util.StringTokenizer;
public class Main{
public static void main(String[] args) throws IOException {
Reader.init(System.in);
int n = Reader.nextInt();
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
set.add(Reader.nextInt());
}
int res = 1;
while (set.contains(res)) {
res++;
}
System.out.println(res);
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
tokenizer = new StringTokenizer("");
}
private static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
使用计数排序方法,还是超时
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main{
static int N = 100000;
static int[] count = new int[N];
public static void main(String[] args) throws IOException {
Reader.init(System.in);
int n = Reader.nextInt();
int num;
for (int i = 0; i < n; i++) {
num = Reader.nextInt();
if(num > 0){
count[num]++;
}
}
for (int i = 1; i < count.length; i++) {
if(count[i] == 0){
System.out.println(i);
return;
}
}
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
tokenizer = new StringTokenizer("");
}
private static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
贴一个C++解法
#include <iostream>
#include <unordered_set>
using namespace std;
int main()
{
ios::sync_with_stdio (false);
int n;
cin >> n;
unordered_set<int> s;
while (n -- )
{
int x;
cin >> x;
s.insert(x);
}
int res = 1;
while (s.count(res)) res ++ ;
cout << res << endl;
return 0;
}