多案例输入,每个案例的输入第一行为一个整数N,表示小白鼠的数目。 下面有N行,每行是一只白鼠的信息。第一个为不大于100的正整数,表示白鼠的重量,;第二个为字符串,表示白鼠的帽子颜色,字符串长度不超过10个字符。 注意:白鼠的重量各不相同。
每个案例按照白鼠的重量从大到小的顺序输出白鼠的帽子颜色。
3 30 red 50 blue 40 green
blue green red
import java.util.Scanner; import java.util.PriorityQueue; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static class Rat { public Rat(int weight, String hat) { this.weight = weight; this.hat = hat; } int weight; String hat; } public static void main(String[] args) { PriorityQueue<Rat> queue = new PriorityQueue<>( (x, y) -> y.weight - x.weight ); Scanner in = new Scanner(System.in); int n = in.nextInt(); for (int i = 0; i < n; i++) { queue.add(new Rat(in.nextInt(), in.next())); } while (!queue.isEmpty()) { System.out.println(queue.poll().hat); } } }
import java.util.Scanner; import java.util.Stack; import java.util.TreeMap; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); TreeMap<Integer, String> map = new TreeMap<>(); for (int i = 0; i <n; i++) { int weight = scanner.nextInt(); String cap = scanner.next(); map.put(weight,cap); } // 默认从小到大遍历,使用Stack进行从大到小遍历 Stack<String> stack = new Stack<>(); for (String value : map.values()) { stack.push(value); } while (!stack.isEmpty()) System.out.println(stack.pop()); } }
import java.util.*; public class Main { public static void main(String[] args) { Scanner reader = new Scanner(System.in); while (reader.hasNext()) { TreeMap<Integer, String> tm = new TreeMap<>((o1, o2) -> o2-o1); int n = reader.nextInt(); for (int i = 0; i < n; ++i) { int weight = reader.nextInt(); String color = reader.next(); tm.put(weight, color); } for (Map.Entry<Integer, String> entry: tm.entrySet()) { System.out.println(entry.getValue()); } } } }
import java.util.Scanner; /* * QQ: 825580813(一起来敲代码) * 思路: * 1, 开辟一个大小为101的String数组 * 2, 将小白鼠的重量作为下标, 帽子颜色作为数组值 * 3, 从后往前输出 非null 的数组值 */ public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n; while (sc.hasNext()) { n = sc.nextInt(); String[] hatColor = new String[101]; for (int i = 0; i < n; ++i) { hatColor[sc.nextInt()] = sc.next(); } for (int i = hatColor.length - 1; i > 0; --i) { if (hatColor[i] != null) { System.out.println(hatColor[i]); } } } sc.close(); } }