[剑指offer]最小的K个数
思路:
使用优先级队列(最大堆)保存这K个数,每次只和堆顶比,如果比顶堆小就删除堆顶,新数入堆,在堆大小等于K时就不用加入数了,直接将堆中的数都add进list中
实现:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> list = new ArrayList<>();
        int len = input.length;
        if(k > len || k == 0){
            return list;
        }
        PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(k,new Comparator<Integer>(){
            public int compare(Integer o1,Integer o2){
                return o2.compareTo(o1);
            }
        });
        for(int i = 0;i < len ;i++){
            if(maxHeap.size() != k){
                maxHeap.offer(input[i]);
            }
            else if(maxHeap.peek() > input[i]){
                Integer temp = maxHeap.poll();
                temp = null;
                maxHeap.offer(input[i]);
            }
        }
        for(Integer integer : maxHeap){
            list.add(integer);
        }
        return list;
    }
}

相关文章:

  • 2021-08-26
  • 2022-01-27
  • 2022-12-23
  • 2022-12-23
  • 2021-12-05
  • 2022-12-23
  • 2019-11-29
猜你喜欢
  • 2021-07-20
  • 2021-08-08
  • 2022-12-23
  • 2021-08-08
  • 2021-04-21
  • 2021-07-17
相关资源
相似解决方案