题目:一个长度为n的不递减数列,可以操作任意次(也可以不操作),每一次操作可以让某一个位置上的数加1,但是每个位置最多只能操作一次,现在想问通过这个操作,能让新产生的数列中最多有多少个不同的数(重复的数算一个)
输入描述:每一个文件输入第一行输入一个整数T(1<=T<=1000)
,代表有T组测试数据。接下来T组,每一组第一行输入一个整数n(1<n<10^5)。接下来输入n个整数,a[i] (1<a[i]<2*n)代表序列中的每一个元素。数据保证每一个文件内的n的综合不超过100000。
输入
2
6
1 2 2 2 5 6
2
4 4
输出
5
2
说明:对于数组[1,2,2,2,5,6]当修改后为[1,2,3,2,5,6]时最多有5个不同的数
import org.omg.CORBA.INTERNAL;
import java.util.*;
/**
* @author
* @create 2021-04-02 19:18
*/
public class test2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int groupNum = scan.nextInt();//获取输入的第一行的数字,代表测试组数
int[][] arr = new int[groupNum][];//定义二维数组来接受测试用例,每个测试用例是一个一维数组
for (int i = 0; i < groupNum; i++) {
int arrLength = scan.nextInt();//获取第二行输入数组的长度
scan.nextLine();//去除空行
String s = scan.nextLine();//获取一行输入数组,为字符串类型
//定义temp数组来接受字符串数组的每一个数存放到该数组中
int[] temp = new int[s.length() / 2 + 1];
int index = 0;
for (int k = 0; k < s.length(); k+=2) {
temp[index] = s.charAt(k) - 48;
index++;
}
arr[i] = temp;
}
scan.close();
for (int[] num: arr) {
HashSet<Integer> set = new HashSet<>();
set.add(num[0]);
for (int i = 1; i < num.length; i++) {
if (set.contains(num[i])){
set.add(num[i]+1);
}else {
set.add(num[i]);
}
}
System.out.println(set.size());
}
}
}
下面的代码主要是看一下输入怎么写
public class Exam0402_1_1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
for (int i = 0; i < m; i++) {
int n = sc.nextInt();
int[] nums = new int[n];
for (int j = 0; j < n; j++) {
nums[j] = sc.nextInt();
}
int res = find(nums);
System.out.println(res);
}
sc.close();
}
public static int find(int[] nums){
HashSet<Integer> set = new HashSet<>();
if (nums == null || nums.length == 0){
return 0;
}
set.add(nums[0]);
for (int i = 1; i < nums.length; i++) {
if (set.contains(nums[i])) {
set.add(nums[i] + 1);
} else {
set.add(nums[i]);
}
}
return set.size();
}
}