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

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

题目描述

输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

import java.util.ArrayList;public class Solution {    public ArrayList
GetLeastNumbers_Solution(int [] input, int k) { ArrayList
array = new ArrayList
(); if(input.length
i;j--){ if(input[j]

标准答案:

import java.util.ArrayList;import java.util.PriorityQueue;import java.util.Comparator;public class Solution {   public ArrayList
GetLeastNumbers_Solution(int[] input, int k) { ArrayList
result = new ArrayList
(); int length = input.length; if(k > length || k == 0){ return result; } PriorityQueue
maxHeap = new PriorityQueue
(k, new Comparator
() { @Override public int compare(Integer o1, Integer o2) { return o2.compareTo(o1); } }); for (int i = 0; i < length; 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) { result.add(integer); } return result; }}

另外还有一种方法是基于快排寻找下标为k-1

转载地址:http://nyonn.baihongyu.com/

你可能感兴趣的文章
new、delete和malloc、free详解与混用问题
查看>>
Android 定位当前焦点位置
查看>>
Selinux 配置
查看>>
Intent跳转及传值
查看>>
Linux 手动内存清理
查看>>
Android中Framework重要文件路径
查看>>
乌班图下C++读取文件夹下文件名
查看>>
c++余弦相似度
查看>>
点云全局特征ESF算法原理及实现
查看>>
Shape mismatch: The shape of labels (received (3,)) should equal the shape of logits except for the
查看>>
点云ESF特征分类(神经网络)
查看>>
PCL区域生长分割
查看>>
PCL报错
查看>>
nvcc -v报错nvcc fatal : No input files specified; use option --help for more information
查看>>
乌班图20.04安装noetic版ROS
查看>>
tensorflow2常用命令笔记(一)
查看>>
jupyter自由切换anaconda环境
查看>>
PCL点云随机采样到固定点数
查看>>
C语言游戏开发——1.1 弹跳的小球
查看>>
C程序设计语言——基础概念
查看>>