1. 题目
读题
描述
输入n个整数,找出其中最小的k个整数并按升序输出
本题有多组输入样例
数据范围:1≤�≤1000 1≤n≤1000 ,输入的整数满足 1≤���≤10000 1≤val≤10000
考查点
你需要掌握不同的排序算法,如冒泡排序、快速排序、堆排序等,以及它们的时间复杂度和空间复杂度。
你也需要掌握不同的数据结构,如数组、集合、优先队列、堆等,以及它们的特点和操作方法。
你需要根据题目的要求,选择合适的排序算法和数据结构,来实现高效的解决方案。
2. 解法
思路
代码逻辑
具体实现
方法一:利用数组,先对输入的整数进行排序,然后输出最小的k个数。可以使用Arrays.sort(数组名)方法来排序。例如:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int length = sc.nextInt(); //数组长度
int k = sc.nextInt(); //最小的k个数
int[] arr = new int[length];
for (int i = 0; i < arr.length; ++i) {
arr[i] = sc.nextInt();
}
Arrays.sort(arr);
for (int j = 0; j < k; j++) {
if (j == k - 1) {
System.out.println(arr[j]); //这里必须是println,否则过不了
} else {
System.out.print(arr[j] + " ");
}
}
}
}
}
方法二:利用集合,先将输入的整数存入一个ArrayList,然后使用Collections.sort(集合名)方法来排序,再输出最小的k个数。例如:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int num = sc.nextInt();
int k = sc.nextInt();
ArrayList<Integer> al = new ArrayList<>();
for (int i = 0; i < num; i++) {
al.add(sc.nextInt());
}
Collections.sort(al);
for (int j = 0; j < k; j++) {
if (j == k - 1) {
System.out.println(al.get(j));
} else {
System.out.print(al.get(j) + " ");
}
}
}
}
}
方法三:利用优先队列,先将输入的整数存入一个PriorityQueue,然后使用poll()方法来弹出最小的k个数。例如:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
int k = sc.nextInt();
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int i = 0; i < n; i++) {
pq.offer(sc.nextInt());
}
for (int j = 0; j < k; j++) {
if (j == k - 1) {
System.out.println(pq.poll());
} else {
System.out.print(pq.poll() + " ");
}
}
}
}
}