题解 | Java #输入n个整数,输出其中最小的k个#
输入n个整数,输出其中最小的k个
https://www.nowcoder.com/practice/69ef2267aafd4d52b250a272fd27052c
排序题首先想到通过TreeSet实现自动排序,通过Iterator遍历器实现集合遍历
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); TreeSet<Integer> ts = new TreeSet<>(); int size = sc.nextInt(); int position = sc.nextInt(); if (size < position){ System.out.println("Error"); }else{ while (sc.hasNext()){ int input = sc.nextInt(); ts.add(input); } Iterator<Integer> it = ts.iterator(); for (int i = 0; i < position; i++){ System.out.print(it.next() + " "); } } } }