leetcode 215. Kth Largest Element in an Array
来源:互联网 发布:南方大数据300a怎么样 编辑:程序博客网 时间:2024/06/04 18:57
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<Integer> p = new PriorityQueue<Integer>(); for(int i=0; i<nums.length;i++){ p.add(nums[i]); if(p.size()>k) p.poll(); } return p.poll(); }}
0 0
- Leetcode Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- [LeetCode] Kth Largest Element in an Array
- [leetcode] Kth Largest Element in an Array
- leetcode--Kth Largest Element in an Array
- #leetcode#Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- 【Leetcode】Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- Kth Largest Element in an Array -- leetcode
- [Leetcode]Kth Largest Element in an Array
- [LeetCode]Kth Largest Element in an Array
- *LeetCode-Kth Largest Element in an Array
- LeetCode----Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- leetcode-Kth Largest Element in an Array
- LeetCode -- Kth Largest Element in an Array
- 题目96 n-1位数
- 基于STM32和W5500的Modbus TCP通讯
- I/O多路转接之select
- 多个UITableView 或者Scrollview 置顶问题
- 机器学习面试问题6
- leetcode 215. Kth Largest Element in an Array
- 三维空间两直线/线段最短距离、线段计算算法
- 源码实现ArrayList的常用方法
- 用websocket爬去来疯的实时聊天数据
- EasyDarwin开源流媒体云平台VS调试断点提示“还没有为该文档加载任何符号”的解决办法
- 定时向文件写内容
- git-remote-https.exe-无法找到入口
- Cause: java.sql.SQLException: The user specified as a definer ('root'@'%') does not exist
- 32个兼职方法,总有一个适合你!