【一次过】【PriorityQueue】【2017好未来】n个数里最小的k个

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/89321987

找出n个数里最小的k个

输入描述:

每个测试输入包含空格分割的n+1个整数,最后一个整数为k值,n
不超过100。

输出描述:

输出n个整数里最小的k个数。升序输出

示例1

输入

3 9 6 8 -10 7 -11 19 30 12 23 5

输出

-11 -10 3 6 7

解题思路:

使用Priority即可。为了保证更高的拓展性,本题采用固定大小的最大堆堆进行输入,然后逆序输出即可。

注意维护好固定最大堆的性质!

import java.util.*;

public class Main {

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        List<Integer> list = new ArrayList<>();
        String[] strs = sc.nextLine().split(" ");
        for(String str : strs)
            list.add(Integer.parseInt(str));

        int num = list.get(list.size() - 1);
        PriorityQueue<Integer> queue = new PriorityQueue<>(11, Collections.reverseOrder());
        for(int i=0; i<list.size()-1; i++){
            if(queue.size() < num)
                queue.offer(list.get(i));
            else{
                if(list.get(i) > queue.peek())
                    continue;
                
                queue.poll();
                queue.offer(list.get(i));
            }
        }

        Stack<Integer> stack = new Stack<>();
        while(!queue.isEmpty()){
            stack.push(queue.poll());
        }

        for(int i=0; i<num-1; i++)
            System.out.print(stack.pop() + " ");
        System.out.print(stack.pop());
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/89321987