题解 | 输入n个整数,输出其中最小的k个
解题重点:
- 整理思路比较简单,先排序,再找前两个
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String[] str = in.nextLine().split(" "); String[] arr = in.nextLine().split(" "); int n = Integer.parseInt(str[0]); int k = Integer.parseInt(str[1]); int[] numArr = new int[n]; for (int i = 0; i < n; i++) { numArr[i] = Integer.parseInt(arr[i]); } for (int i = 0; i < n; i++) { int tmp = numArr[i]; int j = i - 1; while (j >= 0 && numArr[j] > tmp) { numArr[j + 1] = numArr[j]; j--; } numArr[j + 1] = tmp; } for (int i = 0; i < k; i++) { System.out.print(numArr[i] + " " ); } } }