leetcode 215. Kth Largest Element in an Array


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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值