【蓝桥杯2019】修改数组

在这里插入图片描述在这里插入图片描述
看题目很容易想到以下代码

public class Main {
	public static void main(final String[] args) {
		Scanner sc = new Scanner(System.in);
		int n=sc.nextInt();
		List<Integer>list=new ArrayList<>();
		for(int i=0;i<n;i++) {
			Integer num=sc.nextInt();
			while(list.contains(num)) {
				num++;
			}
			list.add(num);
		}
		System.out.println(list);
		sc.close();
	}
}

但是这样只能处理较少情况,遇到特殊数肯定会超时。下面的这种处理方法优化了不少,不是每次+1了,而是直接加相同数字出现过的次数,比如有3个1,第二个1就是+1,第三个直接+2,而不是两次+1,而且每次都记录每次的新值出现的次数,这样循环到新数未出现过为止。

public class Main {
    static int[] a1 = new int[1000010], a2 = new int[1000010];//一个用于输出,一个用于储存节点
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        for (int i = 0; i < a; i++) {
            int count = sc.nextInt();
            for (;;) //循环遍历
            {
                if (a2[count] == 0) { //确定输入的值是否已经存在
                    a2[count]++;//若不存在则标记推出循环
                    break;
                }else {
                    a2[count]++;//若存在则为该标识访问次数加一减少循环次数
                    count +=a2[count] - 1;
                }
            }
            a1[i] = count;
        }
        for (int i = 0; i < a; i++) {
            System.out.print(a1[i] + " ");
        }
    }
}
  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值