博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
剑指 Offer 40. 最小的k个数
阅读量:4035 次
发布时间:2019-05-24

本文共 1018 字,大约阅读时间需要 3 分钟。

题目描述

输入整数数组 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
minheap=new PriorityQueue<>(); for(int c: arr){
minheap.add(c); } for(int i=0;i

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

public class Heap {
//求数组最大的K个数,用Java实现大根堆 static class MaxheapComparator implements Comparator
{
@Override public int compare(Integer o1, Integer o2) {
return o2-o1; //从大到小 } } public int [] maxHeapTest(int [] arr,int k){
int [] a= new int[k]; Queue
maxheap=new PriorityQueue<>(new MaxheapComparator()); for(int c: arr){
maxheap.add(c); } for(int i=0;i
你可能感兴趣的文章
慢慢欣赏linux phy驱动初始化2
查看>>
慢慢欣赏linux CPU占用率学习
查看>>
2020年终总结
查看>>
linux内核学习(4)建立正式内核的页式内存映射, 以x86 32位模式为例
查看>>
Homebrew指令集
查看>>
React Native(一):搭建开发环境、出Hello World
查看>>
React Native(二):属性、状态
查看>>
JSX使用总结
查看>>
React Native(四):布局(使用Flexbox)
查看>>
React Native(七):Android双击Back键退出应用
查看>>
Android自定义apk名称、版本号自增
查看>>
adb command not found
查看>>
Xcode 启动页面禁用和显示
查看>>
【剑指offer】q50:树中结点的最近祖先
查看>>
二叉树的非递归遍历
查看>>
【leetcode】Reorder List (python)
查看>>
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Word Break(python)
查看>>
【剑指offer】面试题26:复杂链表的复制
查看>>