题解 | #元素按照升序或降序进行排序#
输入整型数组和排序标识,对其元素按照升序或降序进行排序
https://www.nowcoder.com/practice/dd0c6b26c9e541f5b935047ff4156309
import java.util.Scanner; import java.util.PriorityQueue; import java.util.Arrays; import java.util.Comparator; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 int count = in.nextInt(); int[] array = new int[count]; int index = 0; while (index < count) { // 注意 while 处理多个 case array[index] = in.nextInt(); index++; } int operate = in.nextInt(); Arrays.sort(array); System.out.println(solution(array, 0 == operate ? true : false)); } public static String solution(int[] array, boolean asc) { PriorityQueue<Integer> queue; if (asc) { queue = new PriorityQueue<>(); } else { queue = new PriorityQueue<>(new Comparator<Integer>() { public int compare(Integer a, Integer b) { return a > b ? -1 : 1; } }); } StringBuffer sbf = new StringBuffer(); for (Integer element : array) { queue.add(element); } while (!queue.isEmpty()) { sbf.append(queue.poll()); sbf.append(" "); } sbf.deleteCharAt(sbf.length() - 1); return sbf.toString(); } }