首页 > 代码库 > 清华复试-成绩排序

清华复试-成绩排序

题目描述

查找和排序

题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩
      都按先录入排列在前的规则处理。

   例示:
   jack      70
   peter     96
   Tom       70
   smith     67

   从高到低  成绩            
   peter     96    
   jack      70    
   Tom       70    
   smith     67    

   从低到高

   smith     67  

   Tom       70    
   jack      70    
   peter     96      

 

解题思路一:

Treemap

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

 思路二:

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

 

清华复试-成绩排序