4. Input n integers and output the smallest k ones.
Title description
Input n integers and output the smallest k ones.
There are multiple input examples for this question, please use loop reading
Example
enter
5 2
1 3 5 7 2
Output
1 2
analysis
1. Enter data with the keyboard as required, n, k, n as the length of the array, and k as the number of returned digits
2. After completing the input as required, call the method in the array, sort, and then splice
Code
import java.util.Arrays;
import java.util.Scanner;
public class Main4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
Arrays.sort(arr);
StringBuilder ss = new StringBuilder();
for (int i = 0; i < k; i++) {
ss.append(arr[i]).append(" ");
}
System.out.println(ss.toString().trim());
}
}
}