题解

这个题居然是入门级别的,我做出来都费老鼻子劲了,看来我太菜。。。

代码

简单实现

import java.util.Scanner;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) throws Exception {
        // 1.输入
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        int sortType = sc.nextInt();

        // 2.排序
        Arrays.sort(arr);

        // 3.输出结果
        if (sortType == 0) {
            for (int i : arr) {
                System.out.print(i + " ");
            }
        } else {
            for (int i = arr.length - 1; i >= 0; i--) {
                System.out.print(arr[i] + " ");
            }
        }
    }
}

Java 8 流实现

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Collections;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws Exception {
        // 1.处理输入内容
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        String[] strs = br.readLine().split(" ");
        int sortType = Integer.parseInt(br.readLine());

        // 2.对数组进行排序
        List<Integer> list = Arrays.stream(strs)
                             .map(Integer::parseInt)
                             .sorted()
                             .collect(Collectors.toList());
        if (sortType == 1) { // 逆序
            Collections.reverse(list);
        }

        // 3.打印结果
        for (int i : list) {
            System.out.print(i + " ");
        }
    }
}