Kth largest numbers ii

来源:互联网 发布:淘宝店铺行业排名 编辑:程序博客网 时间:2024/06/07 18:44

description:
Find K-th largest element in an array. and N is much larger than k.

Notice

You can swap elements in the array

Have you met this question in a real interview? Yes
Example
In array [9,3,2,4,8], the 3rd largest element is 4.

In array [1,2,3,4,5], the 1st largest element is 5, 2nd largest element is 4, 3rd largest element is 3 and etc.

这一道题目,可以使用PriorityQueue来做,
PriorityQueue是一种用于解决Top K问题的非常好的手段。插入方法的(offer、remove、poll、add)的时间复杂度都是O(logn); size、peek的时间复杂度为 O(1)

class Solution {    /**     * @param nums an integer unsorted array     * @param k an integer from 1 to n     * @return the kth largest element     */    public int kthLargestElement2(int[] nums, int k) {        // Write your code here        PriorityQueue<Integer> pq = new PriorityQueue<>(k);        for (int num : nums) {            pq.offer(num);            if (pq.size() > k) {                pq.poll();            }         }        return pq.peek();    }}
0 0
原创粉丝点击