【Java】蓝桥杯 PREV - 5 错误票据

一、题目描述

二、代码(此题此处提供两种思路)

2.1 使用字符串分割读取整数

2.1.1 代码

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);

		int N = in.nextInt();
		ArrayList<Integer> aList = new ArrayList<Integer>();
		in.nextLine();
		String[] tmp = new String[N];
		String[][] tmp_split = new String[N][];
		for(int i = 0; i < N; i++){
			tmp[i] = in.nextLine();
			tmp[i].trim();
//			System.out.println("-------" + i + "----------");
//			System.out.println(tmp[i]);
//			System.out.println("---------------------------");
			tmp_split[i] = tmp[i].split("\\s+");
//			System.out.println(tmp_split[i]);
		}
		in.close();
		for(int i = 0; i < N; i++){
			for(int j = 0; j < tmp_split[i].length; j++){
				aList.add(Integer.valueOf(tmp_split[i][j]));
			}
		}
		
		int repeat = 0;
		int error = 0;
		
		Collections.sort(aList);
//		System.out.println(aList);
		
		for(int i = 0; i < aList.size() - 1; i++){
			int front = aList.get(i);
			int forward = aList.get(i + 1);
			if(front < forward - 1)
				error = front + 1;
			if(front == forward)
				repeat = front;
		}
		
		System.out.println(error + " " + repeat);
		
	}
		
}

2.1.2 思路记录

  1. 开辟两个字符串数组(分别为一维数组 a 和二维数组 b ),一维数组 a 存放 “每一行的输入”、并使用 trim() 函数去除前导空白和尾部空白;二维数组 b 存放 经过 split("\\s+") 函数处理、拆分后的 a 数组。
  2. 使用 ArrayList 存放数组 b 中的数字,注意,需统一变量数据形式。
  3. 直接使用排序函数。
  4. 后续较简单,略。 

2.1.3 结果


2.2 直接开辟大数组存放整数

2.2.1 代码




import java.util.Scanner;






public class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);

		int N = in.nextInt();
		int error = 0;
		int repeat = 0;
		in.nextLine();
		
		int[] harsh = new int[10001];
		
		int max = Integer.MIN_VALUE;
		int min = Integer.MAX_VALUE;
		for(int i = 0; i < N; i++){
			
			String s = in.nextLine();
			Scanner scanner = new Scanner(s);
			while(scanner.hasNextInt()){
				
				int tmp = scanner.nextInt();
				harsh[tmp]++;
				max = Math.max(max, tmp);
				min = Math.min(min, tmp);
			}
			scanner.close();
		}
//		while(in.hasNextInt()){
//			int tmp = in.nextInt();
//			harsh[tmp]++;
//			max = Math.max(max, tmp);
//			min = Math.min(min, tmp);
//		}
		in.close();
		for(int i = min; i <= max; i++){
			if(harsh[i] == 2)
				repeat = i;
			if(harsh[i] == 0)
				error = i;
				
		}
		
		System.out.println(error + " " + repeat);
 	}
		
		
	
	
	

}

2.2.2 思路记录

  1. 开辟一个数组 harsh,如果读入的数是 a , 那么将 harsh[a] 加 1;使用两个变量 max 和 min 监控输入的数的范围,方便后续遍历。
  2. 遍历输入的数的范围,如果 a 输入两次,则 harsh[a] == 2,该数 a 为重复的数字。同理可得若 harsh[a] == 1,则该数 a 为缺失的数字。
  3. 该思路简单粗暴,但估计数据量过大,妥妥超时和超内存。

2.2.3 结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值