其他分享
首页 > 其他分享> > 剑指offer之最小的K个数(堆、排序、优先队列)

剑指offer之最小的K个数(堆、排序、优先队列)

作者:互联网

问题

给定一个数组,找出其中最小的K个数。例如数组元素是4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。如果K>数组的长度,那么返回一个空的数组。

思路

采用最大堆对数组进行存储,当堆中的长度大于k时,进行出堆,将剩余k个数据按要求返回。

代码

import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Comparator;
public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList <Integer> result = new ArrayList<>();
        if (k > input.length){
            return result;
        }
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(new Comparator<Integer>(){
        //大顶堆
        @Override
        public int compare(Integer i1,Integer i2){
            return i2-i1;//降序排列,小顶堆中是i1-i2
        }
        });//注意括号位置和数量
        for(int i= 0;i < input.length;i++){
           maxHeap.offer(input[i]);
       }
       while(maxHeap.size()> k){
           maxHeap.poll();
       }
        while(!maxHeap.isEmpty()){
            result.add(maxHeap.poll());
        }
       return result;
    }
}

 

标签:offer,队列,ArrayList,maxHeap,int,result,数组,input,排序
来源: https://blog.csdn.net/codepandacode/article/details/114950272