题解 | #输入n个整数,输出其中最小的k个#

输入n个整数,输出其中最小的k个

http://www.nowcoder.com/practice/69ef2267aafd4d52b250a272fd27052c


public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextInt()) {
            ArrayList<Integer> list = new ArrayList<>();
            int n = sc.nextInt();
            int k = sc.nextInt();
            String sk = sc.nextLine();
            String s = sc.nextLine();
            String[] ss = s.split(" ");
            int[] nums = new int[n];
            for (int i = 0; i < n; i++) {
                nums[i] = Integer.parseInt(ss[i]);
                list.add(nums[i]);
            }
            Collections.sort(list);
            for (int i = 0; i < k; i++) {
                if(i == k-1){
                    System.out.println(list.get(i));
                    break;
                }
                System.out.print(list.get(i)+" ");
            }
        }
    }
}
全部评论

相关推荐

千千倩倩:简历问题有点多,加v细聊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务