PTA 猜数字 Java

该博客介绍了如何使用Java解决PTA平台上的猜数字问题。通过创建一个以数字为下标、玩家名字为值的数组,计算平均值的一半并进行搜索,找到位于该位置的玩家即为赢家。博客特别提醒注意四舍五入的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PTA 猜数字 Java

在这里插入图片描述

思路:题目保证了赢家是唯一的,故直接用数字做下标,玩家名字做值,构成一个String[] 数组。然后计算出平均值的一半,取整后从当前位置左右搜索,一旦找到玩家,则该玩家就是赢家。仔细点可以考虑四舍五入谁更近的情况

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;

public class Main {
	public static void main(String[] args) throws IOException {
		Reader.init(System.in);
		int N = Reader.nextInt();
		String[] names = new String[101];
		int sum = 0;
		for (int i = 0; i < N; i++) {
			String name = Reader.next();
			int num = Reader.nextInt();
			names[num] = name;
			sum += num;
		}
		float avg = (float) (1.0 * sum / N / 2);
		sum = (int) (avg + 0.5);
		int pre = sum, after = sum;
		int index = sum;
        while (names[index] == null) {
			if (after <= 100) {
				index = after++;
				if (names[index] != null) {
					break;
				}
			}
			if (pre >= 0) {
				index = pre--;
				if (names[index] != null) {
					break;
				}
			}
		}
		System.out.println((int) avg + " " + names[index]);
	}
}

// Class for buffered reading int and double values *//*
class Reader {
	static BufferedReader reader;
	static StringTokenizer tokenizer;

	// ** call this method to initialize reader for InputStream *//*
	static void init(InputStream input) {
		reader = new BufferedReader(new InputStreamReader(input));
		tokenizer = new StringTokenizer("");
	}

	static void init(File file) {
		try {
			reader = new BufferedReader(new FileReader(file));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		tokenizer = new StringTokenizer("");
	}

	// ** get next word *//*
	static String next() throws IOException {
		while (!tokenizer.hasMoreTokens()) {
			// TODO add check for eof if necessary
			tokenizer = new StringTokenizer(reader.readLine());
		}
		return tokenizer.nextToken();
	}

	static String nextLine() throws IOException {
		return reader.readLine();
	}

	static int nextInt() throws IOException {
		return Integer.parseInt(next());
	}

	static char nextChar() throws IOException {
		return next().toCharArray()[0];
	}

	static float nextFloat() throws IOException {
		return Float.parseFloat(next());
	}

	static Double nextDouble() throws IOException {
		return Double.parseDouble(next());
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值