LeetCode-Kth Largest Element in an Array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/86611126

Description:
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.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

Note:

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

题意:给定一个未排序的数组和一个正数k,返回数组中第k大的元素;

解法:碰到诸如第k大或者前k个最大元素,常利用堆来实现,对应的有最小堆和最大堆两种;本地要求返回数组中的第k大的元素,那么,我们可以利用数组元素构建一个最大堆,这样循环k-1次将堆顶的元素移出,则此时堆顶的元素就是数组中第k大的元素;这里我们使用优先队列来模拟实现最大堆;

Java
class Solution {
    public int findKthLargest(int[] nums, int k) {
        Queue<Integer> heap = new PriorityQueue<>((a, b) -> b - a);
        for (int num: nums)
            heap.add(num);
        while (k-- > 1)
            heap.poll();
        return heap.peek();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/86611126