测试用例及预期结果如下:
因为只需要前k个小的数,所以不需要全部排序,我直接使用直接插入排序将需要的数字排到前面来,即可满足要求。
下面是具体代码:
import java.util.*;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Y
* Date: 2019-07-09
* Time: 22:46
*/
public class Main {
private static String getMinK(String s) {
StringBuilder stringBuilder = new StringBuilder();
String[] strs = s.split(" ");
int[] ints = new int[strs.length-1];
int k = Integer.valueOf(strs[strs.length - 1]);
for (int i = 0; i < ints.length - 1; i++) {
ints[i] = Integer.valueOf(strs[i]);
}
for (int i = 0; i < k; i++) {
int m=ints[i];
for (int j = i; j < ints.length-1; j++) {
if (ints[j] < m) {
m = ints[j];
int tmp=ints[i];
ints[i]=ints[j];
ints[j]=tmp;
}
}
ints[i] = m;
stringBuilder.append(ints[i] + " ");
}
return stringBuilder.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
System.out.println(getMinK(s));
}
}