题解 | #成绩排序# 用例居然有重名的,至少应该说一声吧
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int sort = in.nextInt(); in.nextLine(); Map<String, Integer> map = new LinkedHashMap<>(); while (in.hasNextLine()) { String nameAndScore = in.nextLine(); String[] arr = nameAndScore.split(" "); int score = Integer.valueOf(arr[1]); map.put(nameAndScore, score);//用例居然有重名的,所以用"name score"来做key来防止重名.如果说重名又重分,那就会舍弃一个,好在用例没有这样的 } List<String> keys = new ArrayList<>(map.keySet()); int flag = sort == 1 ? 1 : -1;//升序还是降序 keys.sort((t1, t2)->(flag * (map.get(t1) - map.get(t2)))); for (String key : keys) { System.out.println(key); } } }