查找和排序java
題目:輸入任意(用戶,成績)序列,能夠得到成績從高到低或從低到高的排列,相同成績
都按先錄入排列在前的規則處理。ide
例示:
jack 70
peter 96
Tom 70
smith 67ui
從高到低 成績
peter 96
jack 70
Tom 70
smith 67 blog
從低到高排序
smith 67 get
Tom 70
jack 70
peter 96 it
解題思路一:io
Treemapclass
package com.tonyluis.oj; import java.util.*; import java.util.Map.*; public class Main { public static void main(String[] args) { @SuppressWarnings("resource") Scanner in = new Scanner(System.in); TreeMap<Integer, List<String>> treeMap = new TreeMap<Integer, List<String>>(); while (in.hasNext()) { int num = in.nextInt(); int state = in.nextInt(); for (int i = 0; i < num; i++) { String name = in.next(); int score = in.nextInt(); if (treeMap.containsKey(score)) treeMap.get(score).add(name); else { List<String> list = new ArrayList<String>(); list.add(name); treeMap.put(score, list); } } List<Entry<Integer, List<String>>> list = new ArrayList<Entry<Integer, List<String>>>(treeMap.entrySet()); if (state == 0) Collections.reverse(list); for (Entry<Integer, List<String>> entry : list) for (String s : entry.getValue()) System.out.println(s + " " + entry.getKey()); treeMap.clear(); } } }
思路二:import
LinkedHashMap+Comparator
import java.util.*; import java.util.Map.*; public class Main { public static void main(String[] args) { @SuppressWarnings("resource") Scanner in = new Scanner(System.in); LinkedHashMap<Integer, List<String>> hm = new LinkedHashMap<Integer, List<String>>(); while (in.hasNext()) { int num = in.nextInt(); int state = in.nextInt(); for (int i = 0; i < num; i++) { String name = in.next(); int score = in.nextInt(); if (hm.containsKey(score)) hm.get(score).add(name); else { List<String> list = new ArrayList<String>(); list.add(name); hm.put(score, list); } } List<Entry<Integer, List<String>>> list = new ArrayList<Entry<Integer, List<String>>>(hm.entrySet()); Comparator<Entry<Integer, List<String>>> c1 = new Comparator<Entry<Integer, List<String>>>() { @Override public int compare(Entry<Integer, List<String>> arg0, Entry<Integer, List<String>> arg1) { // TODO Auto-generated method stub return arg0.getKey() - arg1.getKey(); } }; Comparator<Entry<Integer, List<String>>> c2 = new Comparator<Entry<Integer, List<String>>>() { @Override public int compare(Entry<Integer, List<String>> arg0, Entry<Integer, List<String>> arg1) { // TODO Auto-generated method stub return arg1.getKey() - arg0.getKey(); } }; if (state == 1) Collections.sort(list, c1); else Collections.sort(list, c2); for (Entry<Integer, List<String>> entry : list) for (String s : entry.getValue()) System.out.println(s + " " + entry.getKey()); hm.clear(); } } }