华为机试-HJ58 输入n个整数,输出其中最小的k个

81 阅读1分钟

题目

image.png

www.nowcoder.com/practice/69…

我的题解

import java.io.*;
import java.util.*;

public class Main {
    public static void main (String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String str = bf.readLine();
        String[] arr = str.split("\\s+");
        Integer total = Integer.parseInt(arr[0]);
        Integer orderTotal = Integer.parseInt(arr[1]);

        String str1 = bf.readLine();
        bf.close();
        String[] arr1 = str1.split("\\s+");
        int[] intArr = new int[total];
        for (int i = 0; i < total; i++) {
            intArr[i] = Integer.parseInt(arr1[i]);
        }

        Arrays.sort(intArr);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < orderTotal; i++) {
            sb.append(intArr[i]).append(" ");
        }
        System.out.println(sb.toString().trim());
    }
}

image.png

总结:

1、 核心点:Arrays.sort(intArr);