PTA 猜数字 Java

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());
	}
}

发布了27 篇原创文章 · 获赞 2 · 访问量 1467

猜你喜欢

转载自blog.csdn.net/Samil_Hy/article/details/104208966