map的应用
输入n(n<=100)个整数,按照绝对值从大到小排序后输出。题目保证对于每一个测试实例,所有的数的绝对值都不相等。
1 import java.text.DecimalFormat; 2 import java.util.Arrays; 3 import java.util.HashMap; 4 import java.util.Map; 5 import java.util.Scanner; 6 7 public class Main { 8 public static void main(String[] args) { 9 @SuppressWarnings("resource") 10 Scanner in = new Scanner(System.in); 11 DecimalFormat df = new DecimalFormat("#0.00"); 12 while (in.hasNextInt()) { 13 int n = in.nextInt(); 14 if (n == 0) 15 return; 16 int[] arr = new int[n]; 17 for (int i = 0; i < n; ++i) { 18 arr[i] = in.nextInt(); 19 } 20 sortArray(arr); 21 } 22 } 23 24 private static void sortArray(int[] arr) { 25 // TODO Auto-generated method stub 26 int[] newArr = new int[arr.length]; 27 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 28 for (int i = 0, len = arr.length; i < len; i++) { 29 newArr[i] = Math.abs(arr[i]); 30 map.put(newArr[i], arr[i]); 31 } 32 Arrays.sort(newArr); 33 System.out.print(map.get(newArr[newArr.length - 1])); 34 for (int i = newArr.length - 2; i >= 0; --i) { 35 System.out.print(" " + map.get(newArr[i])); 36 } 37 System.out.println(); 38 } 39 }