题解 | #活用Comparator#
输入整型数组和排序标识,对其元素按照升序或降序进行排序
https://www.nowcoder.com/practice/dd0c6b26c9e541f5b935047ff4156309
import java.util.Scanner; import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()){ int nums = in.nextInt(); Integer[] tar=new Integer[nums]; for (int i = 0; i <nums ; i++) { tar[i]=in.nextInt(); } int method = in.nextInt(); Arrays.sort(tar, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if (method==0){ return o1-o2; }else { return o2-o1; } } }); for (int i = 0; i <nums ; i++) { System.out.print(tar[i]+" "); } } } }