博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 215. Kth Largest Element in an Array
阅读量:7102 次
发布时间:2019-06-28

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

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,

Given [3,2,1,5,6,4] and k = 2, return 5.

Note: 

You may assume k is always valid, 1 ≤ k ≤ array's length.

 

题意:

给出一个未排序的数组,找出数组中第K大的元素。

 

方法:

使用优先级队列来解决。

优先级队列是不同于先进先出队列的另一种队列,每次从队列中取出的是具有最高优先权的元素。

如果不是提供comparator的话,优先队列中的元素默认按照自然顺序排列,

也就是数字小的默认在队列头,字符串按照字典顺序排列。

public class Solution {    //优先队列,    //遍历数组时将数字加入优先队列(堆),一旦堆的大小大于k就将堆顶元素去除,    //确保堆的大小为k,    public int findKthLargest(int[] nums, int k) {        PriorityQueue
p = new PriorityQueue
(); for(int i=0; i
k) p.poll(); } return p.poll(); }}

 

转载于:https://www.cnblogs.com/iwangzheng/p/5717943.html

你可能感兴趣的文章
linux 中的sar命令 与gnuplot绘图
查看>>
解决网站遭CC攻击(转载)
查看>>
Spring 项目全介绍
查看>>
Android应用程序组件Content Provider的启动过程源代码分析(3)
查看>>
部署及配置ISCSI Target,Livemigration系列之三
查看>>
rundeck Web页面配置node节点
查看>>
Java程序员,笔试必读
查看>>
linux 下 eclipse 开发环境的搭建
查看>>
android中DatePicker&TimePicker的应用
查看>>
JavaScript和C#通用gb2312和utf8编码解码函数简单实现
查看>>
在创建触发器时出现不能在 'inserted' 表和 'deleted' 表中使用 text、ntext 或 image 列...
查看>>
sql server 2012序列号
查看>>
一步一步带你实现virtual dom(一)
查看>>
android:http
查看>>
详解JAVA实现支付宝接口编程
查看>>
HTTP 请求返回代码含义
查看>>
python+soket实现UDP协议的客户/服务端中文聊天程序
查看>>
android:使用BaseExpandableListAdapter实现可折叠的列表
查看>>
什么时候用存储过程
查看>>
【MongoDB for Java】Java操作MongoDB
查看>>