這一關感覺還沒第三關難,思路很清晰
題目
1004 成績排名
讀入?n(>0)名學生的姓名、學號、成績,分別輸出成績最高和成績最低學生的姓名和學號。
輸入格式:
每個測試輸入包含 1 個測試用例,格式為
第 1 行:正整數 n 第 2 行:第 1 個學生的姓名 學號 成績 第 3 行:第 2 個學生的姓名 學號 成績... ... ... 第 n+1 行:第 n 個學生的姓名 學號 成績
其中
姓名
和學號
均為不超過 10 個字符的字符串,成績為 0 到 100 之間的一個整數,這里保證在一組測試用例中沒有兩個學生的成績是相同的。輸出格式:
對每個測試用例輸出 2 行,第 1 行是成績最高學生的姓名和學號,第 2 行是成績最低學生的姓名和學號,字符串間有 1 空格。
輸入樣例:
3 Joe Math990112 89 Mike CS991301 100 Mary EE990830 95
輸出樣例:
Mike CS991301 Joe Math990112
解題思路
- 首先,和第三關一樣把值存在lis中然后去掉不相關第一條數據;
- 其次,參考樣例把字符串在第二個空格出進行拆分,分為成績和名字,放入map中;
- 最后,把成績單獨放入一個集合中排序,最后取最大最小值作為map的key取出姓名。
代碼
import java.util.*;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);scanner.useDelimiter("\n"); // 使用換行符作為分隔符List<String> inputList = new ArrayList<>();while (scanner.hasNext()) {String str = scanner.next().trim(); // 去除字符串前后的空格if (str.isEmpty()) {break; // 如果輸入為空行,則結束循環}inputList.add(str);}inputList.remove(0);Map<String, String> scoreMap = new TreeMap<>();//使用Collections.reverseOrder()方法來創建一個比較器,該比較器按照整數的逆序進行排序。// Comparator.comparingInt(Integer::parseInt)是一個函數引用,它根據元素的整數值進行比較。Set<String> sortSet = new TreeSet<>(Collections.reverseOrder(Comparator.comparingInt(Integer::parseInt)));inputList.forEach(str -> {String name = "";String score = "";int firstSpaceIndex = str.indexOf(' ');if (firstSpaceIndex != -1) {int secondSpaceIndex = str.indexOf(' ', firstSpaceIndex + 1);if (secondSpaceIndex != -1) {//取字符串第二空格前數據name = str.substring(0, secondSpaceIndex);//取字符串第二個空格后數據score = str.substring(secondSpaceIndex + 1);}}scoreMap.put(score,name);sortSet.add(score);});//打印出最高成績和最低成績的名字System.out.println(sortSet);System.out.println(scoreMap.get(sortSet.toArray(new String[0])[0]));//因為是倒序所以第一個肯定是最大,最后(sortSet.size() - 1)為最小System.out.println(scoreMap.get(sortSet.toArray(new String[0])[sortSet.size() - 1]));}
}