剑指 Offer 40. 最小的k个数

题目描述
输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。

示例 1:

输入:arr = [3,2,1], k = 2
输出:[1,2] 或者 [2,1]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Java

class Solution {
    public int[] getLeastNumbers(int[] arr, int k) {
            //小根堆测试,java优先队列默认是小根堆
        int [] a= new int[k];
        Queue<Integer> minheap=new PriorityQueue<>();
        for(int c: arr){
            minheap.add(c);
        }
        for(int i=0;i<k;i++){
            a[i]=minheap.poll();
        }
        return a;  
    } 
}

扩展,如果求前K个最大数,

public class Heap {

    //求数组最大的K个数,用Java实现大根堆
    static  class MaxheapComparator implements Comparator<Integer>{
        @Override
        public int compare(Integer o1, Integer o2) {
            return  o2-o1;  //从大到小
        }
    }
    public  int []  maxHeapTest(int [] arr,int k){
        int [] a= new int[k];
        Queue<Integer> maxheap=new PriorityQueue<>(new MaxheapComparator());
        for(int c: arr){
            maxheap.add(c);
        }
        for(int i=0;i<k;i++){
            a[i]=maxheap.poll();
        }
        return a;
    }
    //求数组最大的K个数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值