问题描述
小F手中有一个包含nn个自然数的集合(集合中的数字可能会重复出现)。他可以对集合中的数字进行若干次操作,每次操作可以选择集合中的一个数字xx,并将其替换为一个大于xx的数字yy。小F的目标是通过这些操作,使得集合中最大的未出现的自然数KK尽可能大。你的任务是计算出这个最大的KK值。
测试样例
样例1:
输入:
n = 5, a = [5, 0, 0, 2, 2]
输出:4
样例2:
输入:
n = 6, a = [1, 0, 3, 4, 4, 5]
输出:2
样例3:
输入:
n = 4, a = [0, 1, 2, 3]
输出:4
样例4:
输入:
n = 7, a = [7, 6, 5, 4, 3, 2, 1]
输出:0
样例5:
输入:
n = 5, a = [0, 1, 2, 1, 3]
输出:5
题解:
请忽略题目的叙述,只会越看越迷糊。直接看样例,发现这道题就是在做将a数组变成一个严格递增且每两个元素差一的数组,你只能将元素放大,而第一个缺少的元素及为你要找的值。
举例,样例1中的0 0 2 2 5,可以化为0 1 2 3 5,缺少4。
而当能化为严格递增数组时,比如样例3,就直接输出下一个数。
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<queue>
#include<stack>
#include<vector>
#include<unordered_set>
#include<unordered_map>
#include<map>
#include<set>
using namespace std;
typedef long long int ll;
int cmp(int a,int b){
return a<b;
}
int solution(int n, vector<int> a) {
// write code here
int i,j;
int ans=0;
sort(a.begin(),a.end(),cmp);
for(i=0;i<a.size();i++){
if(a[i]<=ans){
ans++;
}
else{
return ans;
}
}
return ans;
}
int main() {
cout << (solution(5, {5, 0, 0, 2, 2}) == 4) << endl;
cout << (solution(6, {1, 0, 3, 4, 4, 5}) == 2) << endl;
cout << (solution(4, {0, 1, 2, 3}) == 4) << endl;
cout << (solution(7, {7, 6, 5, 4, 3, 2, 1}) == 0) << endl;
cout << (solution(5, {0, 1, 2, 1, 3}) == 5) << endl;
return 0;
}