"Sword Finger Offer"-29, the smallest number of K

1. Knowledge points of this question

heap

2. Title description

Enter n integers and find the smallest K numbers. For example, if you enter the 8 numbers 4,5,1,6,2,7,3,8, the smallest 4 numbers are 1,2,3,4.

3. Problem solving ideas

Establish a priority queue with the largest heap with a capacity of k. Traverse the elements once, if the size of the queue is <k, enter the queue directly, otherwise, let the current element compare with the top element of the team, if the top element of the team is larger, then dequeue and enqueue the current element.

4. Code

public class Solution {
    
    
    public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
    
    
        ArrayList<Integer> list = new ArrayList<>();
        // k 不能大于数组长度或者小于等于 0
        if (k > input.length || k <= 0) {
    
    
            return list;
        }
        // 最大堆
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Collections.reverseOrder());
        // 遍历数组构建最大堆
        for (int i : input) {
    
    
            // 当最大堆元素个数小于 k 时,直接入队
            if (priorityQueue.size() < k) {
    
    
                priorityQueue.offer(i);
            } else {
    
    
                // 否则,让当前元素和与根比较,如果如果根大于当前元素,则根出队,当前元素入队
                if (priorityQueue.peek() > i) {
    
    
                    priorityQueue.poll();
                    priorityQueue.offer(i);
                }
            }
        }
        // 将最大堆根元素逐个输出
        while (priorityQueue.peek() != null) {
    
    
            list.add(priorityQueue.poll());
        }
        // 反转顺序
        Collections.reverse(list);
        return list;
    }
}

Guess you like

Origin blog.csdn.net/bm1998/article/details/112937238