【2021阿里实习笔试】0402场第一题

这篇博客主要介绍了一个Java程序,用于解决给定一个不递减数列,通过允许对任意位置的数加1(每个位置最多一次),求解最多能产生多少个不同数的问题。程序首先读取输入的测试用例数量和每个测试用例的数组长度,然后处理每个数组,使用HashSet记录不同数的数量。最后输出每个测试用例的结果。示例输入包括两组测试数据,输出分别为5和2。
摘要由CSDN通过智能技术生成

题目:一个长度为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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值